【问题标题】:jQuery ajax and CORS not workingjQuery ajax 和 CORS 不起作用
【发布时间】:2016-09-23 10:46:24
【问题描述】:

我正在尝试从 WepApi2 控制器获取 json 响应

[EnableCors(origin = "*", methods = "*", headers = "*")]
public class DataController {
    public IEnumerable<int> GetData(RequestItems items) {
        ...
    }
}

使用它来尝试获取数据...

$.ajax({
  type: "POST",
  method: "POST",
  contentType: "application/json",
  url: "https://api.mysite.com/api/Data/GetData",
  data: JSON.stringify({ /* some data here */ }),
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "*",
    "Access-Control-Allow-Headers": "*"
  },
  xhrFields: {
       withCredentials: true
  },
  success: function(xhr) {
       console.log(xhr);
  },
  error: function(e) {
       console.log(e);
  }
});

我得到了这个......

跨域请求被阻止:同源策略不允许读取 远程资源在 https://api.mysite.com/api/Data/GetData。 (原因:CORS 标头 'Access-Control-Allow-Origin' 与 '*' 不匹配)

我几乎在网上找到了关于 CORS 和 jQuery 的所有信息,但我不知道该怎么做。请帮忙!

【问题讨论】:

  • 仅供参考,ASP.NET WebApi 的 CORS 包已安装,因此 EnabedCors
  • 如果我必须调试它,我会打开浏览器的开发工具,转到网络选项卡并查看 HTTP 标头。我假设 jQuery 期望 Access-Control-Allow-Origin 为 *,但标头丢失或设置为不同的值。

标签: jquery asp.net-web-api cors


【解决方案1】:

我将 CORS 与 WebAPI 一起使用,没有任何问题。也许我会描述一下我的工作。如果它不相关,我将删除答案。不过这对我有用。

编辑:另外请注意,CORS 的标头必须作为响应。

我当然使用OWIN。我的Startup.cs 看起来像:

public static void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
    WebApiConfig.Register(config);

    app.UseWebApi(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}

请注意,我必须在我的 WebApiConfig 上明确地 EnableCors。然后当然继续app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

然后像你一样在我的 ApiController 类上启用 cors:

[EnableCors("*", "*", "GET,POST")]
public class FauxDBController : ApiController
{
    [HttpPost]
    [AllowAnonymous]
    public mJSONSQLFAUXResponse XYZ(mJSONSQLFAUX data)
    {
    }
}

只是为了展示我使用的 NuGet 包,这里是我的packages.config

<packages>
  <package id="Microsoft.AspNet.Cors" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.Cors" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />
  <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />
  <package id="Microsoft.Owin" version="3.0.1" targetFramework="net452" />
  <package id="Microsoft.Owin.Cors" version="3.0.1" targetFramework="net452" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />
  <package id="Owin" version="1.0" targetFramework="net452" />
</packages>

最后,我不使用jQuery,但我的angular.js 带有ajax 例程的文件看起来像:

$http.post('http://localhost:59113/api/FauxDB/XYZ', { }).success(function (data, status, headers, config) {
    // something..
}).error(function (data, status, headers, config) {
    // something..
});

希望对你有帮助。

【讨论】:

    【解决方案2】:

    您可以按照以下步骤操作 -

    1. WebAPI 项目 - 在 web.config 中添加这个 -

    <system.webServer>
        <modules>
          <remove name="FormsAuthentication" />
        </modules>
        <httpProtocol>
          <!-- THESE HEADERS ARE IMPORTANT TO WORK WITH CORS -->
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
            <add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
          </customHeaders>
        </httpProtocol>
        <handlers>
          <remove name="WebDAV" />
          <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>

    2.API Global.asax 添加这个-

    protected void Application_BeginRequest(object sender, EventArgs e)
          {
               //this is required to work with CORS request
                if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
                {
                    HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                    HttpContext.Current.Response.End();
                }
            }  
    

    3.在JS文件中这样调用——

            function LoadReport() {
                var data = {};
                var URL = APIBaseUrl + '/api/statements/get_user_statements?instance_id=1';
    
                $.support.cors = true;
                $.ajax({
                    contentType: false,
                    processData: false,
                    beforeSend: function (req) {
                        req.setRequestHeader('Authorization', 'Bearer ' + access_token);
                    },
                    crossDomain: true,
                    url: URL,
                    type: 'GET',           
                    success: function (response) {
                        alert('yes');
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert('try again');
                    }
                });
            }

    【讨论】:

      猜你喜欢
      • 2014-01-01
      • 1970-01-01
      • 2019-08-01
      • 2014-01-05
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多