Asp.net WebAPI对Ajax和Angularjs跨域的支持

什么是跨域请求?

假设我们请求的地址A:http://api.xx.com/api/GetAllPeople,那如果在B页面 http://www.baidu.com/tlzzu.html中使用POST去调用外部接口的话,B页面会先向A地址发送一个OPTIONS类型(OPTIONS并不是webapi中的一个方法名,而是一种请求类型,类似POST、GET等)的预检请求(Preflight Request)只要对这种请求返回200就可以,具体内容不作检验。执行成功后会再次对A接口进行正常请求。返回数据。

跨域请求的解决方式:
1. 使用JQuery的jsonp(这种方式很简单,但是只适合jquery,原生ajax和angularjs并不支持
2. 通过配置WebApi的Response 响应头

配置WebApi

如何配置呢?大致分为二步:
1.修改web.config
2. 重写Application_BeginRequest方法

修改web.config

如果不新增配置将会报错:
XMLHttpRequest cannot load [URL]. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘[URL]’ is therefore not allowed access. The response had HTTP status code 405.

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
        <add name="Access-Control-Max-Age" value="30" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <!--<remove name="OPTIONSVerbHandler" />-->
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

  </system.webServer>

新增了配置后,部署到IIS中,ajax跨域请求能正常响应,如果是在本机IIS Express时,那么还需要做第二步操作,重写Application_BeginRequest方法

重写Application_BeginRequest

在重写Application_BeginRequest之前还需要注意一点,在IIS Express中,ajax中的url不能写http://127.0.0.1:xxx/xxx
应当写http://localhost:xxx/xxx,否则还会报第一个错误。

如果写法正确,第一步新增web.config也实现了,还会报如下错误:
405 Method Not Allowed:XMLHttpRequest cannot load [url]. Response for preflight has invalid HTTP status code 405

那么请在API的Global.asax新增:

        protected void Application_BeginRequest(object sender, System.EventArgs e)
        {
            var req = System.Web.HttpContext.Current.Request;
            if (req.HttpMethod == "OPTIONS")//过滤options请求,用于js跨域
            {
                Response.StatusCode = 200;
                Response.SubStatusCode = 200;
                Response.End();
            }
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值