部署 ASP.NET API 时 PUT 和 DELETE 方法中出现 CORS 错误

问题描述 投票:0回答:1

我实现了一个

ASP.NET API (.NET 8)
。当我调试时,所有端点都可以正常工作,但是当我将此 API 部署到本地 IIS 中时,它会抛出以下错误:

Access to fetch at 'https://localhost:7162/Scene' from origin 'http://localhost:3001' 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.

这个错误发生在

HttpPut
HttpDelete
端点上,正如我所说,当它部署到我的本地IIS中时。

我已经像这样配置了我的 CORS 策略:

app.UseCors(x => x
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());

如果有人可以帮助我解决可能发生的事情,我将非常感激。

谢谢大家!

c# asp.net .net asp.net-web-api cors
1个回答
0
投票

确保在 Startup.cs 中的 app.UseAuthorization() 之前和 app.UseRouting() 之后调用 app.UseCors。它们出现的顺序至关重要

此外,在 web.config 文件中,您可能需要添加特定设置以允许所有标头或应用程序工作所需的标头。

 <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
          </customHeaders>
        </httpProtocol>
    </system.webServer>
© www.soinside.com 2019 - 2024. All rights reserved.