.NET 4.8 ASP.NET Web API CORS问题:预检请求无HTTP OK状态
.NET 4.8 Web API 浏览器CORS预检OPTIONS 404错误排查建议
针对你遇到的浏览器JS调用Web API时OPTIONS预检请求返回404,但Postman/Insomnia调用正常的问题,可按以下步骤排查:
1. 先修正前端请求URL的语法错误
从你提供的请求URL能看到末尾有多余的}:
https://xxxxx.xx.xxx.xx:8053/api/account/Createsomething?id=123}
这个无效符号会直接导致请求指向不存在的资源,先检查前端代码的URL拼接逻辑,去掉多余符号,确保请求地址格式正确。
2. 完善Global.asax的OPTIONS请求处理逻辑
原代码仅调用Flush()未设置正确的响应状态码和头信息,OPTIONS预检请求需要返回200/204状态码才能通过浏览器校验,修改代码如下:
protected void Application_BeginRequest(object sender, EventArgs e) { var request = HttpContext.Current.Request; var response = HttpContext.Current.Response; if (request.HttpMethod == "OPTIONS") { // 设置CORS响应头 response.Headers.Add("Access-Control-Allow-Origin", "https://xxx.crm4.dynamics.com"); response.Headers.Add("Access-Control-Allow-Credentials", "true"); response.Headers.Add("Access-Control-Allow-Headers", "*"); response.Headers.Add("Access-Control-Allow-Methods", "*"); // 返回204 No Content状态码 response.StatusCode = 204; // 直接结束请求,避免后续路由处理 response.End(); } }
3. 验证Web API路由配置匹配性
确认WebApiConfig.cs中的路由规则能正确匹配请求URL,比如你的路由模板是否包含action参数:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
若路由未包含action,则api/account/Createsomething无法被正确识别,会直接返回404。
4. 检查IIS处理程序映射的动词设置
打开IIS管理器,进入站点的处理程序映射,找到ExtensionlessUrlHandler-Integrated-4.0:
- 右键选择「编辑」,点击「请求限制」
- 切换到「动词」选项卡,确保选择「所有动词」,或手动添加
OPTIONS - 保存配置后重启站点
5. 针对OPTIONS请求跳过Windows认证
由于你启用了Windows认证,而OPTIONS预检请求是匿名发起的,容易被认证拦截。可在web.config中添加location节点,允许OPTIONS请求匿名访问:
<location path="." inheritInChildApplications="false"> <system.web> <authorization> <allow verbs="OPTIONS" users="*"/> <deny users="?"/> </authorization> </system.web> </location>
6. 改用官方CORS包替代手动配置
卸载手动添加的web.config CORS头,安装NuGet包Microsoft.AspNet.WebApi.Cors,然后在WebApiConfig.cs中配置:
using System.Web.Http.Cors; public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 启用CORS var cors = new EnableCorsAttribute("https://xxx.crm4.dynamics.com", "*", "*") { SupportsCredentials = true }; config.EnableCors(cors); // 路由配置... } }
官方包会自动处理预检请求的逻辑,比手动配置更可靠。
7. 排查URL重写规则(若有配置)
如果站点启用了URL重写模块,检查重写规则是否会修改或拦截OPTIONS请求。可添加条件排除OPTIONS请求:
<rule name="xxx" stopProcessing="true"> <match url="xxx"/> <conditions> <add input="{REQUEST_METHOD}" pattern="OPTIONS" negate="true"/> </conditions> <action type="xxx"/> </rule>
内容的提问来源于stack exchange,提问作者Toby Fieldgroove
相关产品推荐
相关产品推荐

