简体   繁体   English

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

[英]c# Web Api with CORS Enabled and the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource

I have a C# Web API project. 我有一个C#Web API项目。 I created a Controller using the Web API 2 standard. 我使用Web API 2标准创建了一个Controller。 I am trying to enable CORS on only one action, this is what I have: 我试图只在一个动作上启用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);
        }
    }
}

My WebApiConfig.cs looks like this: 我的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 };

Here is the Cross-Domain AJAX call: 这是跨域AJAX调用:

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

Based off tutorials such as this one: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works , I should have everything properly setup. 基于这样的教程: http//www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works ,我应该拥有一切正确设置。

I continue to get the following error in Chrome: 我在Chrome中继续收到以下错误:

XMLHttpRequest cannot load http://myurl.com/api/mycontroller . XMLHttpRequest无法加载http://myurl.com/api/mycontroller No 'Access-Control-Allow-Origin' header is present on the requested resource. 请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin ' http://link.myurl.com ' is therefore not allowed access. 因此,不允许来源“ http://link.myurl.com ”访问。

When I take a look at the calls using Fiddler, I notice that the Pre-flight Origin check goes through fine with Status 200, but when the actual call is made it returns 500. 当我看一下使用Fiddler的电话时,我注意到飞行前原点检查在状态200下运行正常,但是当进行实际通话时它返回500。

Interestingly enough, the transactions are committed to the database even though the call failed. 有趣的是,即使呼叫失败,事务也会提交到数据库。 It's almost like the Pre-flight Origin check is running through the code when it should just be checking for Allow Origin. 它几乎就像是飞行前原点检查正在运行代码时应该检查允许原点。

I've tried adding the following to web.config: 我已经尝试将以下内容添加到web.config:

<system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="http://link.myurl.com" />
     </customHeaders>
   </httpProtocol>
 <system.webServer>

If I leave the [EnableCors] line, then I get an error that two values are specified ( http://link.myurl.com ) when there can only be one. 如果我离开[EnableCors]行,那么当只能有一个值时,我会收到指定两个值( http://link.myurl.com )的错误。 If I remove the [EnabledCors] line, I get the original error. 如果我删除[EnabledCors]行,我会收到原始错误。

If you can't already tell, I'm at a loss here. 如果你还不能说,我在这里不知所措。 Ironically it is working (database actions being committed), but the browser thinks its not working and never accepts the JSON return data. 具有讽刺意味的是它正在工作(提交数据库操作),但是浏览器认为它不起作用并且从不接受JSON返回数据。

HELP? 救命?

I'm not sure why this worked this time around, but I got it working. 我不确定这次为什么会这样,但我确实有效。 The main difference might be the library I installed using NuGet: 主要区别可能是我使用NuGet安装的库:

Microsoft ASP.NET Web API 2.2 Cross-Origin Support Microsoft ASP.NET Web API 2.2跨源支持

I then set the WebApiConfig.cs file as specified in my initial post, as well as the EnableCors option above the Action I wanted to allow it on. 然后我按照我的初始帖子中指定的方式设置WebApiConfig.cs文件,以及我希望允许它启用的Action上方的EnableCors选项。

I did NOT set anything in the web.config file. 我没有在web.config文件中设置任何内容。

I no longer receive the error, must have something to do with the NuGet package. 我不再收到错误,必须与NuGet包有关。

I got caught out by this. 我被这个抓住了。 You have to EnableCORS after the routes attribute have been mapped if using Attribute routing. 如果使用属性路由,则必须在映射了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(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS所请求的资源上没有“ Access-Control-Allow-Origin”标头 - CORS No 'Access-Control-Allow-Origin' header is present on the requested resource CORS - 没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource 请求的资源上不存在“Access-Control-Allow-Origin”header。 当启用 CORS 时 - No 'Access-Control-Allow-Origin' header is present on the requested resource. when CORS is enabled Web API 2 CORS不存在“ Access-Control-Allow-Origin”标头 - web api 2 CORS No 'Access-Control-Allow-Origin' header is present MVC web api:请求的资源上不存在“Access-Control-Allow-Origin”标头 - MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource Web API中的请求资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource in web api 使用C#和jQuery在预检请求中的请求资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource in preflight request using c# and jQuery 调用我的 API 时在我的反应应用程序上出现此 CORS 错误 - 请求的资源上不存在“Access-Control-Allow-Origin” header - Getting this CORS error on my react app when calling my API - No 'Access-Control-Allow-Origin' header is present on the requested resource 反应 .NET 启用 CORS - 没有'Access-Control-Allow-Origin' header 出现在请求的资源上 - React .NET Enable CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource Web API 2 C#中出现跨源错误-原因:缺少CORS标头&#39;Access-Control-Allow-Origin&#39; - cross origin error in web api 2 c# - Reason: CORS header 'Access-Control-Allow-Origin' missing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM