【发布时间】:2020-11-01 21:57:15
【问题描述】:
我有一个在本地 IP https://192.168.188.31:44302 上运行的 ASP.NET Core 服务器,带有 Web API 端点。
我可以使用 VS Code REST Client 连接到所述服务器。
现在我想通过在 https://192.168.188.31:5555 上运行的 Blazor WebAssembly 连接到 Web API。
我的 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.
我是 web 开发的新手,发现你必须在服务器端 ASP.NET Core 项目上启用 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 应用程序中调用错误?
【问题讨论】:
-
你是在服务器上配置 CORS 对吧?代码不清楚。
-
是的,最后一个代码摘录来自我的服务器端 ASP.NET Core 项目的文件
startup.cs。我是否还必须配置其他东西(或更多)? -
Configure() 方法对添加项目的顺序很敏感,最好发布完整版。
-
在你的原产地你有:55555(5x5)的错误它指出:5555(4x5),这只是一个错字吗?
-
@CobyC 你的眼光真好,正确的端口是 5555 - 我修好了,但仍然是同样的错误。
标签: c# asp.net-core cors blazor blazor-webassembly