简体   繁体   English

如何在 Blazor Static ZC6E190B284633C48E39E55049DA3CCEZ 应用程序中启用 CORS?

[英]How to enable CORS in Blazor Static Web App?

I have tried every other ways to set Access-Control-Allow-Origin: * in my Blazor Static Web App.我已经尝试了所有其他方法来设置Access-Control-Allow-Origin: *在我的 Blazor Static Web 应用程序中。

I follow this documentation Configure Azure Static Web Apps first to set globalHeaders .我按照此文档配置 Azure Static Web 应用程序首先设置globalHeaders It isn't working.它不工作。

And I try to add Cors in builder services.我尝试在构建器服务中添加 Cors 。 It isn't working too.它也不起作用。

        builder.Services.AddScoped (sp => new HttpClient 
        { BaseAddress = new Uri(builder.Configuration["API_Prefix"] ??
        builder.HostEnvironment.BaseAddress) });

        builder.Services.AddCors(options => 
        { options.AddPolicy(name: policyName,
                  builder =>
                  { builder.WithOrigins("https://localhost:5000") // specifying the allowed origin
                        .WithMethods("GET") // defining the allowed HTTP method
                        .AllowAnyHeader(); // allowing any header to be sent
                  });
        }); 
        await builder.Build().RunAsync();

And I tried it also in individual HttpClient request in the following.我也在下面的单个HttpClient请求中尝试了它。

        // create request object
        var request = new HttpRequestMessage(HttpMethod.Get, uri);

        // add custom http header
        request.Headers.Add("Access-Control-Allow-Origin", "*");
        request.Headers.Add("Access-Control-Allow-Methods", "GET");

        // send request
        var httpResponse = await Http.SendAsync(request);

I had used this tutorial to create [Blazor Static Web App].我使用本教程创建了 [Blazor Static Web 应用程序]。 2 2

This is the error I got in the browser's console.这是我在浏览器控制台中遇到的错误。CORS 错误 ]. ]。 3 3

What am I missing to set the correct configuration?我缺少什么来设置正确的配置?

Restrict Domain consumption of services by CORS browser restriction.通过 CORS 浏览器限制来限制服务的域消费。 But when you hit the service service will get executed but the response wont captured in browser side.但是当您点击服务时,服务将被执行,但响应不会在浏览器端捕获。 By adding following code in API program.cs will allow specific Domains通过在API program.cs中添加以下代码将允许特定域

    builder.Services.AddCors(options =>
    {
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("http://192.168.10.127",
                            "https://localhost:5000",
                            "https://localhost:5001")
                            .AllowAnyHeader()
                            .AllowAnyMethod();
    });
});

app.UseCors();

To allow from any Domain follow below code要允许来自任何域,请遵循以下代码

app.UseCors(options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());

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

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