支持ajax跨域調用的WCF搭建示例

支持ajax 跨域調用的WCF搭建

1.新建一個"ASP.NET空Web應用程序"項目。

2.新建一個「WCF服務(支持ajax)」。

3.修改WCFAjaxService.svc下的WCFAjaxService.svc.cs文件

以下所示(示例):web

 

namespace WCF_Ajax跨域調用示例
{
    [ServiceContract(Namespace = "WCF_Ajax跨域調用示例")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
    public class WCFAjaxService
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public List<UserInfo> GetUser()
        {
            return new List<UserInfo>(){
            new UserInfo(){Id=1,Name="jayjay1"},new UserInfo(){Id=2,Name="jayjay2"}};
        }
    }

    [DataContract]
    public class UserInfo
    {
        [DataMember]
        public int Id { get; set; }
    [DataMember]
    public string Name { get; set; } } }

 

注意別忘了給Service打上ajax

[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]json

標記。跨域

4.修改Web.config配置文件

 

<system.serviceModel>
      <bindings>
        <webHttpBinding>
          <binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"></binding>
        </webHttpBinding>
      </bindings>
        <behaviors>
            <endpointBehaviors>
                <behavior name="AjaxServiceAspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
            multipleSiteBindingsEnabled="true"/>
        <services>
            <service name="AjaxService">
                <endpoint address="" behaviorConfiguration="AjaxServiceAspNetAjaxBehavior"
                    binding="webHttpBinding" bindingConfiguration="HttpJsonBinding" contract="AjaxService" />
            </service>
        </services>
    </system.serviceModel>

 

注意,配置文件中添加了jsonp

<bindings>
        <webHttpBinding>
          <binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"></binding>
        </webHttpBinding>
      </bindings>

節點,並在endpoint節點中添加了網站

bindingConfiguration="HttpJsonBinding"ui

5.調用方式

在另外一個網站中使用url

 

$.ajax({
                url: "http://localhost:46318/WCFAjaxService.svc/GetUser?jsoncallback=?",
                type: "get",
                dataType: "jsonp",
                success: function (data) {
                    alert(data[0]);
                }
            });

 

調用。spa

從返回報文中能夠看出數據以jsonp格式跨域返回。code

jsonp1430098026913([{"__type":"UserInfo:#WCF_Ajax%E8%B7%A8%E5%9F%9F%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B","Id":1,"Name":"jayjay1"},{"__type":"UserInfo:#WCF_Ajax%E8%B7%A8%E5%9F%9F%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B","Id":2,"Name":"jayjay2"}]);

data[0]指的是取第一個json對象,如 data[0].Name取到「jayjay1」 。

相關文章
相關標籤/搜索