我的方法中有這個配置Startup,顯然一切正常
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("https://localhost:5000",
"http://localhost:3000",
"http://localhost:3001")
.AllowAnyHeader()
.WithMethods("PUT", "GET"));
});
app.UseHttpsRedirection();
app.UseCors("MyPolicy");
app.UseRouting();
app.UseAuthorization();
但是當我開始使用另一個未注冊的 url 進行測驗時,請求顯示 cors 錯誤但同時顯示回應,這是否意味著我在未注冊的情況下運行我的服務?
在此螢屏截圖中,您可以看到我向其發出請求的 url

保護我的 API 的正確做法是什么?我還讀到瀏覽器將始終執行請求,即使它不可見
CORS 錯誤,但無論如何都會獲取資料
非常感謝您閱讀我,我是新手
uj5u.com熱心網友回復:
首先,url是http://localhost:44344,所以你需要將它添加到WithOrigins。并且你需要確保請求的方法型別包含在WithMethods("PUT", "GET")。另外,你最好放在和app.UseCors("MyPolicy");之間。app.UseRouting();app.UseAuthorization();
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("https://localhost:5000",
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:44344")
.AllowAnyHeader()
.WithMethods("PUT", "GET"));
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("MyPolicy");
app.UseAuthorization();
uj5u.com熱心網友回復:
Configure 和 ConfigureService 中的 dot.net 代碼是正確的。嘗試允許任何方法并使用來源洗掉。看看你是否可以用郵遞員到達終點
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
uj5u.com熱心網友回復:
在這種情況下,瀏覽器將始終執行請求,這就是它的作業方式。
作為 CORS 之外的一個選項,您可以添加主機過濾。只需將分號分隔的主機名串列添加到您的appsettings.json
{
...
"AllowedHosts": "example1.com;example2.com;localhost"
}
有關詳細資訊,請參閱檔案頁面
同樣從 ASP.NET Core 5Kestrel服務器開始也支持主機過濾 -鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/404849.html
標籤:
