.NET Core 3.1 CORS 不适用于 Ember (3.12) Web UI

J W*_*ezy 4 cross-domain cors ember.js ember-data asp.net-core-3.1

我正在将 .NET Core Web API 从 2.2 迁移到 3.1。我遵循了 Microsoft 迁移说明,并在 UseRouting 和 UseEnpoints 之间调用了 CORS 中间件。但是,我仍然收到 CORS 错误。

在 ConfigureServices 方法中,我有:

services.AddCors();
Run Code Online (Sandbox Code Playgroud)

在配置方法中,我有:

app.UseRouting();

app.UseCors(options => options
        .AllowAnyOrigin()
        .AllowAnyHeader().AllowAnyMethod()
    );

app.UseAuthentication();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)

Web 浏览器中的控制台错误是:

跨域请求被阻止:同源策略不允许读取位于http://localhost:5000/users/login的远程资源。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

跨域请求被阻止:同源策略不允许读取位于http://localhost:5000/users/login的远程资源。(原因:CORS 请求没有成功)。

诊断:

我尝试遵循 Microsoft 的文档Enable Cross-Origin Requests (CORS) in ASP.NET Core,但它使用了过时的引用,例如;使用 Mvc 和 IHostingEnvironment。

我尝试创建一个全新的 Web API 和 Ember Web-UI,但这也不起作用。您可以找到一个简单的示例Getting-started-with-ember-js-and-net-core-3

知道是什么导致了问题?

理想的赏金奖励将用于有效的答案。最好在 Git 上发布一个可以工作的基本项目。

注意:我现在允许任何来源,以便我可以让它工作。最终,这将需要与已启用的 Web-UI 配合使用http://localhost:4200

更新

收到的状态代码是 HTTP 405 - 方法不允许。所讨论的方法是一种 OPTIONS 方法。

J W*_*ezy 12

.NET Core 2.2 到 3.0 迁移文档不正确。调用UseCors();需要放在UseRouting()函数之前。我继续UseHttpsRedirection()在另一个站点的实现中看到它之前添加了它。

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#migrate-startupconfigure

在配置服务中

services.AddCors(options =>
{
    options.AddPolicy("CorsApiPolicy",
    builder =>
    {
        builder.WithOrigins("http://localhost:4200")
            .WithHeaders(new[] { "authorization", "content-type", "accept" })
            .WithMethods(new[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" })
            ;
    });
});
Run Code Online (Sandbox Code Playgroud)

在配置中

app.UseCors("CorsApiPolicy");

//app.UseHttpsRedirection(); 

app.UseJsonApi();

app.UseRouting();

app.UseAuthentication();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!!!微软你们这些杂种。又浪费了我生命中的24小时! (2认同)