Search code examples
blazor-webassembly

Blazor WASM how to get data from .Net 6 API


I’m unable to get data from .Net 6 API into Blazor WASM app.

Firefox shows the on the bottom the very often mentioned error:

enter image description here

I worked on this tutorial: https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-6.0&pivots=webassembly

To fix the CORS Problem I read this document: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

I have no idea what I doing wrong. Please can someone have I look in my demo app on GitHub? I created a simple demo app.

https://github.com/Christoph1972/BlazorTestGetAPIData


Solution

  • for CORS you can do this:

    options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://<YOUR_URL>")//The client Url that wants to get data
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .SetIsOriginAllowed((host) => true));
    

    and

    var app = builder.Build();
    app.UseHttpsRedirection();
    app.UseCors("CorsPolicy"); <-----