c#已启用CORS的Web Api和所请求资源上存在可怕的“Access-Control-Allow-Origin”标头

我有一个C#Web API项目。 我使用Web API 2标准创建了一个Controller。 我试图只在一个动作上启用CORS,这就是我所拥有的:

namespace MyProject.Controllers { public class MyControllerController : ApiController { // POST api/mycontroller [EnableCors("http://link.myurl.com", "*", "*")] public bool Post(MyCustomObject customObject) { // Function that returns Bool return myFunction(customObject); } } } 

我的WebApiConfig.cs看起来像这样:

 // Web API configuration and services config.EnableCors(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Ignore Null values on JSON Returns config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }; 

这是跨域AJAX调用:

 $.ajax({ type: "POST", url: 'http://myurl.com/api/mycontroller', data: JSON.stringify({ Type: 'TextHere', OtherInfo: 'TextHere' }), contentType: "application/json", success: function (data) { } }); 

基于这样的教程: http : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works ,我应该拥有一切正确设置。

我在Chrome中继续收到以下错误:

XMLHttpRequest无法加载http://myurl.com/api/mycontroller 。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此,不允许来源“ http://link.myurl.com ”访问。

当我看一下使用Fiddler的电话时,我注意到状态200的飞行前原点检查正常,但是当实际呼叫发出时它返回500。

有趣的是,即使呼叫失败,事务也会提交到数据库。 它几乎就像是飞行前原点检查正在运行代码时应该检查允许原点。

我已经尝试将以下内容添加到web.config:

        

如果我离开[EnableCors]行,那么当只能有一个值时,我会收到指定两个值( http://link.myurl.com )的错误。 如果我删除[EnabledCors]行,我会收到原始错误。

如果你还不能说,我在这里不知所措。 具有讽刺意味的是它正在工作(提交数据库操作),但浏览器认为它不起作用,并且从不接受JSON返回数据。

救命?

我不确定这次为什么会这样,但我确实有效。 主要区别可能是我使用NuGet安装的库:

Microsoft ASP.NET Web API 2.2跨源支持

然后我按照我的初始post中指定的方式设置WebApiConfig.cs文件,以及我希望允许它启用的Action上方的EnableCors选项。

我没有在web.config文件中设置任何内容。

我不再收到错误,必须与NuGet包有关。

我被这个抓住了。 如果使用属性路由,则必须在映射了routes属性后EnableCORS

 // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Web API configuration and services config.EnableCors();