简体   繁体   中英

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.

I follow this documentation Configure Azure Static Web Apps first to set globalHeaders . It isn't working.

And I try to add Cors in builder services. 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.

        // 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]. 2

This is the error I got in the browser's console.CORS 错误 ]. 3

What am I missing to set the correct configuration?

Restrict Domain consumption of services by CORS browser restriction. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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