各位大大,詢問一下,有人遇過CORS錯誤嗎?
我目前正在練習用SignalR,當網頁嘗試建立連線時,跑出這個錯誤,
按照微軟提供的教學,設置了一遍,但錯誤一樣存在...
[https://docs.microsoft.com/zh-tw/aspnet/core/security/cors?view=aspnetcore-3.1](在 ASP.NET Core 中啟用跨原始來源要求 (CORS))
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://127.0.0.1:5000");
});
});
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseCors(MyAllowSpecificOrigins);
我分別新增了這兩部分
錯誤
Access to fetch at 'http://127.0.0.1:5000/MyHub/negotiate/negotiate?negotiateVersion=1' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
看微軟範例需要一個規範名稱
然後再套用
services.AddCors("Policy1", options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://127.0.0.1:5000");
});
});
app.UseCors("Policy1");
你貼的程式碼我看沒有@@
加上 .AllowCredentials() 試試
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://127.0.0.1:5000").AllowCredentials();
});
});