. net 6中启用CORS时,HTTP PUT, DELETE方法返回405



我在。net 6 Web API项目中遇到了CORS问题。开发从。net 5开始,但后来升级到。net 6。

CORS最初是使用AllowAnyHeaders()AllowAnyMethods()的命名策略启用的,正如这篇Microsoft Docs文章和CodeMaze上的这篇文章所解释的那样。

在开发期间,它在我的本地机器上运行得非常好。然而,当它被部署到测试服务器时,只有GET和POST可以工作。PUT和DELETE不能工作

对于任何控制器的任何端点上的任何PUT或DELETE方法,Postman中的PUT和DELETE请求显示405 method Not Allowed响应。Header的Allow字段显示GET, HEAD, OPTIONS, TRACE。

但是,将PUT更改为OPTIONS仍然会给出405响应,但是Allow字段有DELETE、GET、PUT。

当尝试编辑或删除时,Blazor WASM客户端在控制台中显示以下内容:

Access to fetch at 'http://ip-address:port/api/v1/EndpointName/92b956cd-2290-4270-8df5-056355cab846' from origin 'http://servername:port' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

从那以后,我阅读了MDN上解释CORS的文章,并从各种文章和Stack Overflow帖子中尝试了许多解决方案。

origin适用于.AllowAnyOrigins(),.WithOrigins("*").WithOrigins(list hosts and ports)

标头适用于.AllowAnyHeader().WithHeaders("*")。即使在删除.WithExposedHeaders("X-Pagination")之后,这个头仍然显示并且仍然工作。

.AllowAnyMethod(),.WithMethods("PUT", "DELETE"),.WithMethods("*")均得到上述相同的结果。

Startup.cs文件中的当前代码如下所示:

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
options.AddDefaultPolicy(
policy =>
{
policy.WithOrigins(Configuration["AllowedCORS"]);
policy.AllowAnyMethod();
policy.AllowAnyHeader();
policy.WithExposedHeaders("X-Pagination");
//policy.WithHeaders("*");
//policy.WithMethods("PUT", "DELETE");
//policy.WithMethods("*");
}));
services.AddControllers();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
...
}

非常感谢您对解决这个问题的帮助。

根据我的经验,当iis服务器不允许删除和放置而在开发机器中没有相同的问题时,问题与CORS配置无关,您应该检查两点来找到问题:

首先ExtensionlessUrlHandler-Integrated-4.0:转到IIS管理器中的处理程序映射。找到ExtensionlessUrlHandler-Integrated-4.0,双击它。单击请求限制…按钮,并在Verbs选项卡上,添加DELETE和PUT

第二WebDAVModule也应该允许动词:Check here

最新更新