首页 > 代码库 > WebApi跨域请求

WebApi跨域请求

在实际开发中 会有提供webapi给前端js 直接调用的情况, 这时候就会有存在跨域的情况,

解决方案:

 

在Global中添加代码

   protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.End();
            }
        }

 

在配置文件中加

      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
   <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
      <remove name="WebDav" /> 
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

 

就可以了

 

  $.ajax({
                url: ‘http://api.zxsj.com/api/Job?strName=liuyl‘,
                type: "get", 
                dataType: "json",
                data: {
                    //t: new Date().getDate(), 
                },
                async: true,
                success: function (res) {
                    $(".code").text(res.Code);
                    $(".mess").text(res.Message);
                }
            });

 

WebApi跨域请求