我有一个用 C# 编写的 ASP.NET MVC 和 REST Web API。几天前,我们将 ASP.NET MVC 和 Web API 的框架版本从 4.5 升级到 4.7.2,之后,它不断抛出 CORS 错误,说我的 ASP.NET MVC URL 无法调用 REST
No 'Access-Control-Allow-Origin' header present on the requested resource
有趣的是,当我们几年前开始这个项目时,我们已经配置了此 Answers 中提到的修复程序。到目前为止一切正常。
我什至尝试了该问题的其他答案,但它仍然抛出相同的错误。我什至升级了所有 NuGet 软件包,但遇到了同样的问题。
我通过 Ajax 从 ASP.NET MVC 应用程序调用 API。
这是我的 Global.asax.cs 文件配置
protected void Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS,");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "userId,ApiKey");
HttpContext.Current.Response.End();
}
}
我缺少任何配置吗?
最佳答案
这就是框架升级后它停止为您工作的原因。
在 4.5.2 上,将为 OPTIONS 触发 Application_BeginRequest。
在 4.7.2 上,不会针对 OPTIONS 触发 Application_BeginRequest。
如果您将以下内容添加到 web.config,则 4.7.2 上的 OPTIONS 将会触发 Application_BeginRequest。
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
关于框架从 4.5.2 升级到 4.7.2 后,C# Web API 引发 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65987783/