【问题标题】:Blazor cannot connect to ASP.NET Core WebApi (CORS)Blazor 无法连接到 ASP.NET Core WebApi (CORS)
【发布时间】: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


【解决方案1】:

导致错误消息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(); 中的行 Configure 来停用 HttpsRedirection,或者在函数 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();
        });
});

【讨论】:

    【解决方案2】:

    第 1 步:请在您的 WebAPI 的 Startup.cs 中添加以下代码以允许具有特定来源的 CORS:

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            builder.WithOrigins("https://localhost:44351")
            .AllowAnyHeader()
            .AllowAnyMethod());
        });
    

    第 2 步:现在将上述代码中的“https://localhost:44351”更改为您的 blazor Web 程序集应用程序的 URL。请参阅下面的屏幕截图:

    第 3 步:现在在您的 WebAPI 的 Configure 方法中添加 app.UseCors(),位于 app.UseRouting() 之后和 app.UseRouting() 之前。请参考以下屏幕截图:

    我也遇到了同样的问题,它解决了我的问题。希望它也对你有用。

    注意:无需更改 Blazor Web 汇编代码即可解决上述问题。

    【讨论】:

    • 一开始我错过了“使用您的 blazor Web 程序集应用程序的 URL”。这当然是不同的端口号。一旦我输入了调用 blazor 应用程序的地址,它就工作得很好。
    • @DickdeReus 很高兴知道它对您有用。感谢您的评论。
    • 谢谢!这两个调用也适用于 .NET 6.0(在 Program.cs 中)
    【解决方案3】:

    我不确定默认值是什么,但请尝试使用显式设置:

    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();               
        });
    

    【讨论】:

    • 我试过了,但仍然收到错误消息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.
    • 是的,把 UseCors() 放在 UseAuth*() 之前
    • 我把它放在UseRouting()下面,仍然没有变化。还有什么我可以做的吗?也许我做错了什么?
    • Ik 看起来不错,我看不出错误。也许是 DIY HttpRequestMessage 。找到一个工作样本并比较笔记。
    • 更新:该问题是由于错误颁发的证书(IP 地址不是替代 DNS 名称)。现在一切正常。
    猜你喜欢
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2021-12-13
    • 2019-09-25
    • 2021-04-09
    • 2019-08-30
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多