框架从 4.5.2 升级到 4.7.2 后,C# Web API 引发 CORS 错误

标签 c# ajax asp.net-mvc cors asp.net-web-api2

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

源代码:https://github.com/ShahJe/MVCOptionsDemo

关于框架从 4.5.2 升级到 4.7.2 后,C# Web API 引发 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65987783/

相关文章:

c# - Azure AD - 将所有用户基本信息提取到列表中

c# 如何转换泛型类型

c# - Selenium WebDriver - Chrome - C# - 无法以隐身模式启动 selenium 浏览器作为最大化浏览器

javascript - CSS:特异性不适用于 js 注入(inject)样式表?

c# - Foreach 扩展的更优雅的 LINQ 替代方案

c# - ASP.NET MVC 5 - JSON - (动态?)模型绑定(bind) - REST 服务 - Webhooks - Chargebee

c# - 使用正则表达式 C# 替换 Unicode(泰米尔语)字符串

javascript - 发布或获取 ajax 请求中不存在的数据

php - 使用超链接而不是提交按钮提交 AJAX 表单时出现问题

asp.net-mvc - 如何找出我的 'On-Premises Authority' 网址?