【发布时间】:2021-05-05 08:08:21
【问题描述】:
我有一个用 C# 编写的 ASP.NET MVC 和 REST Web API。几天前,我们将 ASP.NET MVC 和 Web API 的框架版本从 4.5 升级到了 4.7.2,之后,它不断抛出 CORS 错误,说我的 ASP.NET MVC URL 无法调用 REST
请求的资源上不存在“Access-Control-Allow-Origin”标头
有趣的是,当我们几年前开始这个项目时,我们已经配置了 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();
}
}
我缺少任何配置?
【问题讨论】:
-
您是否已恢复到旧版本以确认这实际上导致了问题?在任何情况下,我们都需要您的配置来验证这一点。
-
@Marco 是的,我有,它工作正常。事实上,它也适用于升级的 MVC 版本和旧的 API 构建。
-
然后我们将需要您的 api 配置来为我们自己验证这一点。不看代码,都是猜测。
-
粗略猜测 - 是否需要设置
CompatibilityVersion? SetCompatibilityVersion -
@user1672994 我没有使用 .netcore
标签: c# ajax asp.net-mvc cors asp.net-web-api2