jQuery ajax和CORS不起作用

时间:2022-12-05 13:58:55

I'm trying to get a json response from a WepApi2 controller

我试图从WepApi2控制器获得json响应

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

Using this to try get the data...

用这个来获取数据…

$.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);
  }
});

And I'm getting this...

我得到这个……

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mysite.com/api/Data/GetData. (Reason: CORS header 'Access-Control-Allow-Origin' does not match '*')

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

I've trawled through virtually everything I can find about CORS and jQuery on the web, and I just have no idea what to do. PLEASE HELP!

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

2 个解决方案

#1


3  

I'm using CORS with WebAPI without issues. Perhaps I'll just describe what I do. If it won't be relevant I'll remove answer. This works for me though.

我使用CORS和WebAPI,没有问题。也许我该描述一下我的工作。如果不相关,我将删除答案。这对我很有效。

Edit: Also note, that with CORS the headers have to come in response.

编辑:还要注意,在CORS中,头信息必须是响应的。

I'm of course using the OWIN. My Startup.cs looks like:

我当然在使用OWIN。我的创业公司。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);
}

Notice, that I had to explicitly EnableCors on my WebApiConfig. Then of course continue by app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

请注意,我必须在WebApiConfig上显式启用程序。接下来当然是app.UseCors(microsoft.owin . corsoptions.allowall);

Then just enable cors on my ApiController class as you do:

然后在我的ApiController类上启用cors:

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

Just to show what NuGet packages I use, here is my packages.config:

为了展示我使用的NuGet包,这是我的package .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>

Finally, I don't use jQuery but my angular.js file with ajax routine looks like:

最后,我不使用jQuery而是使用我的角度。js文件的ajax例程如下:

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

Hope it helps.

希望它可以帮助。

#2


0  

You can follow this steps -

你可以遵循以下步骤-

  1. WebAPI project - add this in web.config-
  2. 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 add this-

2。API全球。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.In JS file call this way -

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');
                }
            });
        }

#1


3  

I'm using CORS with WebAPI without issues. Perhaps I'll just describe what I do. If it won't be relevant I'll remove answer. This works for me though.

我使用CORS和WebAPI,没有问题。也许我该描述一下我的工作。如果不相关,我将删除答案。这对我很有效。

Edit: Also note, that with CORS the headers have to come in response.

编辑:还要注意,在CORS中,头信息必须是响应的。

I'm of course using the OWIN. My Startup.cs looks like:

我当然在使用OWIN。我的创业公司。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);
}

Notice, that I had to explicitly EnableCors on my WebApiConfig. Then of course continue by app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

请注意,我必须在WebApiConfig上显式启用程序。接下来当然是app.UseCors(microsoft.owin . corsoptions.allowall);

Then just enable cors on my ApiController class as you do:

然后在我的ApiController类上启用cors:

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

Just to show what NuGet packages I use, here is my packages.config:

为了展示我使用的NuGet包,这是我的package .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>

Finally, I don't use jQuery but my angular.js file with ajax routine looks like:

最后,我不使用jQuery而是使用我的角度。js文件的ajax例程如下:

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

Hope it helps.

希望它可以帮助。

#2


0  

You can follow this steps -

你可以遵循以下步骤-

  1. WebAPI project - add this in web.config-
  2. 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 add this-

2。API全球。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.In JS file call this way -

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');
                }
            });
        }