Blazor 无法连接到 ASP.NET Core WebApi (CORS)

use*_*834 6 c# cors asp.net-core blazor blazor-webassembly

我有一个https://192.168.188.31:44302使用 Web API Enpoints 在本地 IP 上运行的 ASP.NET Core 服务器。我可以使用 VS Code REST 客户端连接到所述服务器。现在我想连接到 Web API,并在https://192.168.188.31:5555.

我的布洛佐代码:

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我现在触发时,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();
}
Run Code Online (Sandbox Code Playgroud)

但我仍然收到上述错误消息。我在配置 CORS 时做错了什么吗?为什么它在 VS Code REST 客户端上按预期工作,以及我如何在 Blazor WASM 应用程序中使调用出错?

use*_*834 5

导致错误消息的问题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

要解决该问题,请HttpsRedirection删除该行来停用app.UseHttpsRedirection();通过删除函数中的Configure停用,或者添加正确的端口以在函数中进行重定向ConfigureServices(推荐方式)。

就我而言,我在端口启动 WebAPI44302,所以我的解决方案如下所示(您必须使其适应您的端口号):

if (Program.IsDevelopment)
{
    services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
        options.HttpsPort = 44302;
    });
}
else
{
    services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
        options.HttpsPort = 443;
    });
}
Run Code Online (Sandbox Code Playgroud)

另请注意,将请求 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();
        });
});
Run Code Online (Sandbox Code Playgroud)


Bri*_*thi 5

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

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

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

在此输入图像描述

步骤 3:现在将 app.UseCors() 添加到 WebAPI 的配置方法中 app.UseRouting() 之后和 app.UseRouting() 之前。请参考下面的屏幕截图:

在此输入图像描述

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

注意:无需更改 Blazor Web 程序集代码即可修复上述问题。