1. 程式人生 > >WebApi跨域請求

WebApi跨域請求

data 配置文件 color bapi .get cti 文件中 cte version

在實際開發中 會有提供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跨域請求