wcf自托管,托管Silverlight4的WCF跨域服务

时间:2011-02-16 05:39来源:博客园 作者:RIVERSPIRIT 点击: 341次
众所周知sl调和网络通信必须要进行跨域验证。这一直以来是很多sl初学者很头痛的问题,解决方案和应用场境也各有不同。今天内cool超人给大家分享一种特别的应用场境。 需求:开发一个给sl调用的服务,使用wcf.tcp绑定,而且客户端使用的是silverlight4 RTM,而这个服务器一个自宿主console应用程序。 问题: 1.跨域服务也必须
众所周知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 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers=""*"">
<domain uri=""*""/>
</allow-from>
<grant-to>
<socket-resource port=""4502-4534"" protocol=""tcp"" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
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来调试本跨域服务。
Tags:  wcf跨平台连接 wcf跨域 wcf自托管

延伸阅读

最新评论

发表评论