美文网首页
支持ajax 跨域调用的WCF配置

支持ajax 跨域调用的WCF配置

作者: ArcherTrister | 来源:发表于2017-11-15 01:24 被阅读0次

1.首先我们需要让我们的操作类支持ajax,把下面的添加到实现类上

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

添加之后是这样的:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class Service1 : IService1

2.在Web.Config配置文件system.serviceModel节点下添加如下配置:

<!--打开aspnet兼容模式-->

<serviceHostingEnvironment multipleSiteBindingsEnabled="true">

<!--添加一个standardEndpoints节点-->

<standardEndpoints>

    <webHttpEndpoint>

        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" crossDomainScriptAccessEnabled="true" />

    </webHttpEndpoint>

</standardEndpoints>

3.右键项目--添加--新建项,选择全局应用程序类(Global.asax)添加,然后打开找到Application_BeginRequest方法添加如下代码:

///移动跨域请求,会请求两次,第一次OPTIONS 空数据请求,为了获取是否允许跨域,

///第二次才是带数据请求,所以为了避免程序上一些Bug,

///空请求时就直接返回,不需要经过业务处理.

protected void Application_BeginRequest(object sender, EventArgs e)       

 {           

     if (HttpContext.Current.Request.HttpMethod == "OPTIONS")            

    {                

        Response.End();            

    }        

}

4.至此完成,亲测可行。注:自己也是第一次接触WCF编程,在网上也搜了好多例子看,基本都是添加服务行为,或者移除IIS的OPTIONSVerbHandler,照着敲下来还是没能解决。

相关文章

网友评论

      本文标题:支持ajax 跨域调用的WCF配置

      本文链接:https://www.haomeiwen.com/subject/vtxwfxtx.html