4

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

我的 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 应用程序中进行错误调用?

4

3 回答 3

4

导致错误消息的问题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(推荐方式)。

就我而言,我在 port 启动我的 WebAPI 44302,所以我的解决方案如下所示(您必须将其调整为您的端口号):

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();
        });
});
于 2020-07-16T17:32:58.733 回答
3

第 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 步:现在在 app.UseRouting() 之后和 app.UseRouting() 之前,在 WebAPI 的 Configure 方法中添加 app.UseCors()。请参考以下屏幕截图:

在此处输入图像描述

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

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

于 2021-03-21T06:43:04.680 回答
0

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

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();               
    });
于 2020-07-14T17:06:13.943 回答