Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor WebAssembly .Net 8 WebAPI CORS Issue

$
0
0

I have the default Blazor APP and I've modified the home page to call an API. When the API initially runs the API works fine, however after a second or two the app refreshes and I see a "TypeError: Failed to fetch". When I look at the console I see the following

Access to fetch at 'https://example.com' from origin 'https://localhost:7280' 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.

So it appears to work while the app is being prerendered but not once fully loaded.

This is my code

BlazorApp1\program.cs

builder.Services.AddHttpClient();builder.Services.AddCors(options =>{    options.AddDefaultPolicy(        policy =>        {            policy.WithOrigins("https://example.com");        });});..app.UseCors();

BlazorApp1.Client\program.cs

builder.Services.AddScoped(sp => new HttpClient());

BlazorApp1.Client\Pages\Home.Razor

@page "/"@inject HttpClient Httpresponse: @resptext@code {    public string resptext { get; set; } = "";    protected override async Task OnInitializedAsync() {            var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com");            request.Headers.Add("oid", "00000000-0000-0000-0000-000000000000");            try            {                var response = await Http.SendAsync(request);                resptext = await response.Content.ReadAsStringAsync();            }            catch (Exception ex)            {                resptext = ex.Message;            }    }}

With the APP running if I run Chrome disabling CORS it works fine

"C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\temp\chrome"

I think the problem is I need to add the CORS policy to the BlazorApp1.Client project but I'm not sure how to do this?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>