启用了 CORS 的 c# Web Api 并且请求的资源上存在可怕的 No 'Access-Control-Allow-Origin' header

标签 c# asp.net ajax asp.net-web-api cors

我有一个 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 cannot load http://myurl.com/api/mycontroller. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://link.myurl.com' is therefore not allowed access.

当我查看使用 Fiddler 的调用时,我注意到 Pre-flight Origin 检查顺利通过状态 200,但在进行实际调用时返回 500。

有趣的是,即使调用失败,事务也会提交到数据库。这几乎就像飞行前 Origin 检查在代码中运行,而它应该只是检查 Allow Origin。

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

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

如果我离开 [EnableCors] 行,则会收到一条错误消息,指出指定了两个值 ( http://link.myurl.com ),而实际上只能指定一个值。如果我删除 [EnabledCors] 行,我会得到原来的错误。

如果您还不能分辨,那我就不知所措了。具有讽刺意味的是它正在工作(正在提交数据库操作),但浏览器认为它不工作并且从不接受 JSON 返回数据。

帮助?

最佳答案

我不确定为什么这一次会起作用,但我让它起作用了。主要区别可能是我使用 NuGet 安装的库:

Microsoft ASP.NET Web API 2.2 跨源支持

然后我按照我最初的帖子中指定的方式设置 WebApiConfig.cs 文件,以及我想要允许它打开的操作上方的 EnableCors 选项。

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

我不再收到错误,一定与 NuGet 包有关。

关于启用了 CORS 的 c# Web Api 并且请求的资源上存在可怕的 No 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25675172/

相关文章:

c# - 创建并运行 C# 控制台应用程序

c# - 更改值适用于预加载但不适用于 linq 和 ef 中的惰性加载

c# - 除了数据库或注册表之外,保存凭证的最佳位置

jquery - Ajax 无法在 IOS 9.0 Cordova 中工作

javascript - Rails 5.2 AJAX 与部分产生 JS 控制台错误

javascript - 我想在 View 端 javascript 中使用 Controller 中的数据

c# - 是否可以枚举对象中的公共(public)静态字符串?

C# 方法原型(prototype)就像 C++ 中的方法原型(prototype)

c# - 如何在 ASP .NET 中的 Web 窗体控件中实现 CSS 类?

asp.net - JsonResult 在浏览器中显示文件下载