自託管Silverlight4的WCF跨網域服務

來源:互聯網
上載者:User

眾所周知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來調試本跨網域服務。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.