我正在嘗試CORS僅針對GET請求啟用,但我似乎很掙扎。通過閱讀檔案,我了解到這應該可以通過添加WithMethods方法來實作,但對我來說似乎不起作用。相反,我沒有遇到 CORS 錯誤,即使fetch通過POST.
下面是我的代碼
(請注意,我添加 2UseCors只是為了證明我已經嘗試了 2 個多載,但都無濟于事,都回傳正常POST)。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options=>{
options.AddPolicy("customPolicy",policy=>{
policy.WithOrigins("https://customsite.com").WithMethods("GET");
});
});
var app = builder.Build();
app.UseCors("customPolicy");
app.UseCors(options=>{
options.WithOrigins("https://customsite.com").WithMethods("GET");
});
app.MapPost("/", () => "Hello World!");
app.Run();
這是一個錯誤,還是我錯過了什么?
uj5u.com熱心網友回復:
原來檔案https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.withmethods?view=aspnetcore-6.0不是很清楚,但我從Andrew Locks 書籍 ASP NET CORE in Action 2e(第 597 頁)。
該WithMethods方法是允許的,而不是限制性的。默認情況下,默認情況下允許使用簡單的標頭(例如GET,HEAD和POST我們的示例中的),(我不知道如何禁用其中之一)。但是其他方法型別,例如PUT在提供的示例中會失敗。只有在方法中加入正確的名字,比如WithMethods("PUT")才會允許請求參與CORS。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516917.html
