jQuery ajax和CORS无法正常工作

时间:2016-05-25 17:17:19

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

我试图从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   标题&#39; Access-Control-Allow-Origin&#39;不匹配&#39; *&#39;)

我已经在网上搜索了几乎所有关于CORS和jQuery的内容,我根本不知道该怎么做。请帮助!

2 个答案:

答案 0 :(得分:3)

我在没有问题的情况下将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);
}

请注意,我必须在EnableCors上明确WebApiConfig。然后当然继续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..
});

希望它有所帮助。

答案 1 :(得分:0)

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

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

    &#13;
    &#13;
    <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>
    &#13;
    &#13;
    &#13;

    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文件中调用这种方式 -

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