[英]Blazor cannot connect to ASP.NET Core WebApi (CORS)
I have a ASP.NET Core Server running on local IP https://192.168.188.31:44302
with Web API Enpoints. 我可以使用 VS Code REST 客戶端連接到所述服務器。 Now I want to conenct to the Web API with Blazor WebAssembly running on https://192.168.188.31:5555
.
我的 Blozor 代碼:
@page "/login"
@inject HttpClient Http
[ ... some "HTML"-Code ... ]
@code {
private async Task Authenticate()
{
var loginModel = new LoginModel
{
Mail = "some@mail.com",
Password = "s3cr3T"
};
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = ClientB.Classes.Uris.AuthenticateUser(),
Content =
JsonContent.Create(loginModel)
};
var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("responseBody: " + responseBody);
}
public async void LoginSubmit(EditContext editContext)
{
await Authenticate();
Console.WriteLine("Debug: Valid Submit");
}
}
當我現在觸發LoginSubmit
時,我在 Chrome 和 Firefox 的開發者控制台中收到以下錯誤消息: login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' 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.
login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' 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.
我是 web 開發的新手,發現您必須在服務器端 ASP.NET 核心項目上啟用 CORS,所以我擴展了startup.cs
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserDataContext, UserSqliteDataContext>();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:44302",
"https://192.168.188.31:5555",
"https://localhost:44302",
"https://localhost:5555")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
services.AddApiVersioning(x =>
{
...
});
services.AddAuthentication(x =>
...
});
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IViewerService, ViewerService>();
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Program.IsDevelopment = env.IsDevelopment();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Log.Initialize();
}
但我仍然收到上述錯誤消息。 我在配置 CORS 時做錯了嗎? 為什么它與 VS Code REST 客戶端按預期工作,我如何在 Blazor WASM 應用程序中使調用出錯?
導致錯誤消息login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' 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.
login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' 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.
是由HttpsRedirection
引起的。
要解決此問題,請通過刪除行app.UseHttpsRedirection();
來停用HttpsRedirection
; 在 function 在 function Configure
中配置或添加正確的重定向ConfigureServices
(推薦方式)。
就我而言,我在端口44302
啟動我的 WebAPI,所以我的解決方案如下所示(您必須將其調整為您的端口號):
if (Program.IsDevelopment)
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 44302;
});
}
else
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
另請注意,將請求 API 的 IP 地址添加到 CORS 就足夠了,如下所示:
services.AddCors(options =>
{
options.AddPolicy(name: specificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:5555",
"http://192.168.188.31:5444")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
第 1 步:請在 WebAPI 的 Startup.cs 中添加以下代碼,以允許 CORS 具有特定來源:
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://localhost:44351")
.AllowAnyHeader()
.AllowAnyMethod());
});
第 2 步:現在用您的 blazor web 程序集應用程序的 URL 更改上述代碼中的“https://localhost:44351”。 請參考以下屏幕截圖:
第 3 步:現在在 app.UseRouting() 之后和 app.UseRouting() 之前,在 WebAPI 的 Configure 方法中添加 app.UseCors()。 請參考以下屏幕截圖:
我也面臨同樣的問題,它解決了我的問題。 希望它也對你有用。
注意:無需更改 Blazor web 匯編代碼即可修復上述問題。
我不確定默認值是什么,但請嘗試使用顯式設置:
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:44302",
"https://192.168.188.31:55555",
"https://localhost:44302",
"https://localhost:55555")
.AllowAnyHeader()
.AllowAnyMethod();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.