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

时间:2020-07-12 16:07:59

标签: c# asp.net-core cors blazor blazor-webassembly

我有一个使用Web API Enpoints在本地IP https://192.168.188.31:44302上运行的ASP.NET Core Server。 我可以使用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 Client上可以正常使用?在Blazor WASM应用程序中我怎么打错电话?

2 个答案:

答案 0 :(得分:2)

导致错误消息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中添加用于重定向的适当端口(推荐方式)。

在我的情况下,我在端口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();
        });
});

答案 1 :(得分:2)

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

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

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

enter image description here

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

enter image description here

我也遇到了同样的问题,它解决了我的问题。希望它也适用于您。

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