webapi处理OPTIONS请求
报错1信息
Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解决方案
参考资料:https://segmentfault.com/q/1010000016765176,把value值改成特定的域名。
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="http://localhost:9528" /> </httpProtocol> </system.webServer>
报错2信息
Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解决方案
增加一行配置文件
<add name="Access-Control-Allow-Credentials" value="true" />
报错3信息
Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
原因
浏览器请求接口时会发送两个请求,一个是预请求,相当于确认请求,第二个请求才是你要发送的真正的请求,而这个错误信息说明的是第一个OPTINOS请求失败,在服务端没有处理这个method为OPTIONS的请求,需要对它处理一下:
解决方案:
参考资料:关于Web API 2.0中的Options请求返回405的问题
public class SpecialMethodModule : IHttpModule { public SpecialMethodModule() { } public void Init(HttpApplication app) { app.BeginRequest += new EventHandler(this.BeginRequest); } public void Dispose() { } public void BeginRequest(object resource, EventArgs e) { HttpApplication app = resource as HttpApplication; HttpContext context = app.Context; if (context.Request.HttpMethod.ToUpper() == "OPTIONS") { context.Response.StatusCode = 200; context.Response.End(); } } }
在web.config中增加module节点,参考微软官方文档,根据IIS版本不同,增加的节点方式也不同,我是IIS10.0
<configuration> <system.webServer> <modules> <add name="HelloWorldModule" type="HelloWorldModule"/> </modules> </system.webServer> </configuration>
这是我遇到的问题,进行解决以及整理,有其他问题欢迎沟通。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤