CORS 问题仅在 .NET5 上的 PUT 上

问题描述

尝试向我的 .NET5 WebAPI 执行 PUT 请求时收到 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mysiteapi.domain.com/api/v1.0/operations/1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

这些是我在 API 中添加 CORS 的方法

        public static void AddCustomCors(this IServiceCollection services,IWebHostEnvironment env,IConfiguration config)
        {
            var cors = config.GetSection("Cors").Get<CoRSSettings>();
            if (!cors.Enabled)
            {
                return;
            }

            services.AddCors(options =>
            {
                options.AddPolicy("Default",builder =>
                    {
                        builder.WithExposedHeaders(cors.ExposedHeaders)
                            .WithHeaders(cors.Headers)
                            .WithMethods(cors.Methods);
                            .WithOrigins(cors.Origins);

                    });
            });
        }

        public static void UseCustomCors(this IApplicationBuilder app,IConfiguration config)
        {
            var cors = config.GetSection("Cors").Get<CoRSSettings>();
            if (cors.Enabled)
            {
                app.UseCors("Default");
            }
        }

它们在 Startup.cs 中分别作为 ConfigureServicesConfigure 中的第一个方法调用。 设置如下所示:

  "Cors": {
    "Enabled": true,"Origins": [ "http://mysite.domain.com" ],"ExposedHeaders": [ "X-Request-Id","X-Request-Duration" ],"Headers": [ "Content-Type","Authorization","X-Requested-With" ],"Methods": [ "OPTIONS","GET","POST","PUT","DELETE" ]
  }

GET 请求有效,但 PUT 无效。检查网络浏览器选项卡,我看到 OPTIONS 请求没问题,我可以看到我的设置被添加,但在 PUT 请求中它们丢失了。 OPTIONS 请求和响应:

OPTIONS /api/v1.0/operations/1 HTTP/2
Host: mysiteapi.domain.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip,deflate,br
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization,content-type
Referer: https://mysite.domain.com/operation/edit/1
Origin: https://mysite.domain.com
Connection: keep-alive
TE: Trailers


HTTP/2 204 No Content
server: Microsoft-IIS/10.0
access-control-allow-origin: https://mysite.domain.com
access-control-allow-headers: Content-Type,Authorization,X-Requested-With,Origin
access-control-allow-methods: OPTIONS,GET,POST,PUT,DELETE
x-powered-by: ASP.NET
x-powered-by-plesk: PleskWin
date: Thu,28 Jan 2021 16:21:49 GMT
X-Firefox-Spdy: h2

PUT 请求和响应:

PUT /api/v1.0/operations/1 HTTP/2
Host: mysiteapi.domain.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0
Accept: application/json,text/plain,*/*
Accept-Language: en-US,br
Authorization: Bearer <token>
Content-Type: application/json
Content-Length: 353
Origin: https://mysite.domain.com
Connection: keep-alive
Referer: https://mysite.domain.com/operation/edit/1
TE: Trailers

HTTP/2 405 Method Not Allowed
allow: GET,HEAD,OPTIONS,TRACE
content-type: text/html
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET
x-powered-by-plesk: PleskWin
date: Thu,28 Jan 2021 16:21:49 GMT
content-length: 12591
X-Firefox-Spdy: h2

API 位于在 Plesk 18.0.32 中的 IIS 中运行的 Web 主机上。 web.config 如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processpath="dotnet" arguments=".\MySite.WebApi.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
    </system.webServer>
  </location>

  </system.webServer>
  <system.web>
    <compilation tempDirectory="C:\Inetpub\vhosts\mysite.com\tmp" />
    <customErrors mode="Off" />
  </system.web>
</configuration>

我怀疑这是 web.config 的问题,所以我试过了:

  1. 在 web.config添加 Access-Control-Allow-Origin 作为自定义标头 - 这会导致错误,因为它们被添加了两次
  2. 从 API 中删除 CORS 内容并仅从 web.config 添加它们 - 导致有关预检请求的错误
  3. 通过 web.config 删除标题然后添加它 - 导致错误(我认为是预检)
  4. https://docs.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference 中的配置添加到 web.config - 也导致错误

有没有其他人遇到过这个问题?

解决方法

在 web.config 中 <system.webServer> 之前的 <handlers> xml 中包含此内容,以删除可能已禁用 PUT 请求的 webdav。

<modules> 
    <remove name="WebDAVModule" /> 
</modules>