简体   繁体   English

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

[英]Blazor cannot connect to ASP.NET Core WebApi (CORS)

I have a ASP.NET Core Server running on local IP https://192.168.188.31:44302 with Web API Enpoints. I have a ASP.NET Core Server running on local IP https://192.168.188.31:44302 with Web API Enpoints. I can connect to said server with VS Code REST Client.我可以使用 VS Code REST 客户端连接到所述服务器。 Now I want to conenct to the Web API with Blazor WebAssembly running on https://192.168.188.31:5555 . Now I want to conenct to the Web API with Blazor WebAssembly running on https://192.168.188.31:5555 .

My Blozor Code:我的 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");
    }
}

When I now trigger LoginSubmit I get the following error-message in the developer console of Chrome and 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.当我现在触发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. 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.

I'm new to web development and found that you have to enable CORS on the server-side ASP.NET Core project, so I extended startup.cs with我是 web 开发的新手,发现您必须在服务器端 ASP.NET 核心项目上启用 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();
}

But I still get above error message.但我仍然收到上述错误消息。 Am I doing something wrong with configuring CORS?我在配置 CORS 时做错了吗? Why is it working as expected with the VS Code REST Client and how am I making the call wrong in the Blazor WASM application?为什么它与 VS Code REST 客户端按预期工作,我如何在 Blazor WASM 应用程序中使调用出错?

The issue causing the error message 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.导致错误消息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. 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. was caused by HttpsRedirection .是由HttpsRedirection引起的。

To resolve the issue, either deactivate HttpsRedirection by removing the line app.UseHttpsRedirection();要解决此问题,请通过删除行app.UseHttpsRedirection();来停用HttpsRedirection in function Configure or add the proper ports for redirection in function ConfigureServices (recommended way).在 function 在 function Configure中配置或添加正确的重定向ConfigureServices (推荐方式)。

In my case, I start my WebAPI at port 44302 , so my solution looks like this (you have to adapt it to your port number):就我而言,我在端口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;
    });
}

Also note that it is sufficient to add the IP address of the requesting API to CORS like this:另请注意,将请求 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();
        });
});

Step 1: Please add following code in your WebAPI's Startup.cs to allow CORS with specific origins:第 1 步:请在 WebAPI 的 Startup.cs 中添加以下代码,以允许 CORS 具有特定来源:

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

Step 2: Now change "https://localhost:44351" in above code with your blazor web assembly application's URL.第 2 步:现在用您的 blazor web 程序集应用程序的 URL 更改上述代码中的“https://localhost:44351”。 Refer below screen shot:请参考以下屏幕截图:

在此处输入图像描述

Step 3: Now add app.UseCors() in your WebAPI's Configure method after app.UseRouting() and before app.UseRouting().第 3 步:现在在 app.UseRouting() 之后和 app.UseRouting() 之前,在 WebAPI 的 Configure 方法中添加 app.UseCors()。 Please refer below screen shot:请参考以下屏幕截图:

在此处输入图像描述

I was also facing same issue and it solved my problem.我也面临同样的问题,它解决了我的问题。 Hope it will also work for you.希望它也对你有用。

Note: No changes required in Blazor web assembly code to fix the above issue.注意:无需更改 Blazor web 汇编代码即可修复上述问题。

I'm not sure what the defaults are but try it with explicit settings:我不确定默认值是什么,但请尝试使用显式设置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM