gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:27:19 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com