1
votes

I want to get data from ASP.net Core API with HttpClient Factory. I use Microsoft.Extensions.Http package like this :

// Register service in IOC containter 
builder.Services.AddHttpClient<IProductService, ProductService>(option =>
                {
                    option.BaseAddress = new Uri(""/*Base url*/);
                });

// Use in service 
var stream = await _httpClient.GetStreamAsync("");

When I use code in Blazor server side and works correctly. But when I use code in Blazor wasm throw Exception

Access to fetch at 'http client factory base url' from origin 'blazor wasm app url' has been blocked by CORS policy: 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.

No change in ASP.net core API and different results. I use .net core 3.1 in all apps Thanks

1
It seems that you need to enable CORS in Blazor wasm, check Cross-origin resource sharing (CORS) and ASP.NET Core Blazor WebAssembly Cross-origin resource sharing.Zhi Lv
The mechanism isn't different - you're making the calls from different machines. When you use Blazor Server, the HTTP request is made from the server. When you use Blazor WASM, the HTTP call is made from the browser. That's no different than making a fetch call from the browser in Javascript. The browser prevents Javascript pages from calling unrelated URLs as a way to prevent script injection.Panagiotis Kanavos
@brian-parker link is talking about pre-flight pulseARTAV

1 Answers

0
votes

I activate CORS in my API Like this

// In ConfigureServices method
    options.AddPolicy("OpenCors", builder =>
                {
                    builder
                          .AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                      ;
});

// In Configure method
app.UseCors("OpenCors");