自托管Silverlight4的WCF跨域服务

来源:互联网 发布:车辆识别软件 编辑:程序博客网 时间:2024/04/28 18:54

众所周知sl调和网络通信必须要进行跨域验证。这一直以来是很多sl初学者很头痛的问题,解决方案和应用场境也各有不同。今天内cool超人给大家分享一种特别的应用场境。

需求:开发一个给sl调用的服务,使用wcf.tcp绑定,而且客户端使用的是silverlight4 RTM,而这个服务器一个自宿主console应用程序。

问题:

1.跨域服务也必须在宿主的console程序中运行。

2.与逻辑wcf服务相互兼容。

解决方法:

a)首先我们要了解。这从silverlight4RTM发布后,对wcf.tcp的调用的跨域服务改变了检查端口,再也不是943端口了。而改为80端口。这也是很多朋友在使用silverlight4调用wct.tcp一直很郁闷的问题所在。

b)概据以上提示我们可以编写以下代码:

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;

namespace SelfHostedTcpAndSilverlight
{
    [ServiceContract]
    public interface ITcpPolicyRetriever
    {
        [OperationContract, WebGet(UriTemplate = "/clientaccesspolicy.xml")]
        Stream GetSilverlightPolicy();
    }
    public class Service : ITcpPolicyRetriever
    {
        public Stream GetSilverlightPolicy()
        {
            string result = @"

   
       
           
               
           
           
               
           

       

   

";
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
            return new MemoryStream(Encoding.UTF8.GetBytes(result));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string baseAddressHttp = "http://" + Environment.MachineName + ":80";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddressHttp));
            host.AddServiceEndpoint(typeof(ITcpPolicyRetriever), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
            host.Open();
            Console.WriteLine("跨域服务已启动");
            Console.ReadLine();
            host.Close();
        }
    }
}

这样一个自宿主的sl4跨域wcf服务即完成。

PS:这运行这个服务的时候由于程序在本机要注册http服务在win7和vista中是需要管理员权限的。所以内cool超人提醒大家请以管理员权限运行VS来调试本跨域服务。

欢迎您参与更多关于此话题的讨论,本文原创地址为:http://funsl.com

原创粉丝点击