Blazor无法连接到ASP.NET Core WebApi(CORS) [英] Blazor cannot connect to ASP.NET Core WebApi (CORS)

查看:33
本文介绍了Blazor无法连接到ASP.NET Core WebApi(CORS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行在本地IPhttps://192.168.188.31:44302上的ASP.NET Core服务器,带有Web API Enpoints。 我可以用VS码睡觉客户端连接到这个服务器。 现在,我要连接到在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代码睡觉客户端可以按预期工作?我如何在Blazor WASM应用程序中进行错误调用?

推荐答案

导致错误消息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引起的。

若要解决此问题,请通过删除函数Configure中的app.UseHttpsRedirection();行来停用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;
    });
}

还需要注意的是,将请求接口的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();
        });
});

这篇关于Blazor无法连接到ASP.NET Core WebApi(CORS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆