我已经在C# Core中的项目上启用了CORS
I've already enabled CORS on the project in C# Core
在startup.cs中我添加了行
... services.AddCors(); ... app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials());但是当我尝试在另一个Blazor项目中使用API时,在主机上我的API项目的日志中看到了此错误
But when I try to use API in another Blazor project I see in logs in my API project on Host this error
CORS协议不允许指定通配符(任何)来源 和凭据同时显示.通过列出配置策略 如果需要支持凭据,则为单个来源
The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the policy by listing individual origins if credentials needs to be supported
我在Blazor
using (HttpClient http = new HttpClient()) { http.DefaultRequestHeaders.Add("Authorization", "Token"); var response = await http.GetStringAsync("example?prm=2"); Console.WriteLine(response); dynamicContent = response; }启用Cors之前,我会在浏览器控制台中看到另一个错误
Before I enable Cors I see another error in the browser console
要解决此问题我可以改变什么?
What can I change for solving it?
推荐答案您应该已经提供了其余的代码... 这是Blazor客户端应用程序还是Razor组件应用程序(正式称为服务器端Blazor)? 我猜这是Blazor客户端应用程序,对吧? 为什么要实例化HttpClient?您应该改用DI(也许是构造函数注入),注入Blazor本身提供的HttpClient实例.
You should have provided the rest of your code... Is this a Blazor client application or Razor Components application (formally known as Server-Side Blazor) ? I guess this is a Blazor client application, right ? Why do you instantiate an HttpClient ? You should use DI (Perhaps Constructor Injection) instead, injecting an HttpClient instance provided by Blazor itself.
问题可能出在服务器端,尽管它是作为客户端出现的. 请尝试以下操作:
The problem is probably server side, though it surfaces as a client one... Try the following:
获取www.nuget/packages/Microsoft.AspNetCore.Cors/
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); ..... }这:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseCors("CorsPolicy"); }请再次注意:需要在服务器端(而不是直接启用)中启用CORS.请参阅 docs.microsoft/en-us/aspnet/core/security/cors 了解有关如何在ASP.NET Core中启用CORS的详细信息.
Note, once again: CORS needs to be enabled on the server side, not in blazor. See docs.microsoft/en-us/aspnet/core/security/cors for details on how to enable CORS in ASP.NET Core.
blazor:
@page "/<template>" @inject HttpClient Http @functions { protected override async Task OnInitAsync() { var response= await Http.GetJsonAsync<string> ("example?prm=2"); } }希望这对您有帮助...
Hope this helps...
更多推荐
如何解决"CORS协议不允许同时指定通配符(任何)起源和凭证".错误
发布评论