Home > Enterprise >  .Net 6 - UseCors for blazor
.Net 6 - UseCors for blazor

Time:10-30

I am trying to build a blazor app that need to fetch some json from the client side but on a http source that I cannot convert to https and of course I have cors issues on chrome.

      Unhandled exception rendering component: TypeError: Failed to fetch
System.Net.Http.HttpRequestException: TypeError: Failed to fetch
 ---> System.Runtime.InteropServices.JavaScript.JSException: TypeError: Failed to fetch
   at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.GetStringAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at CncGenerator.MachineDashboard.MachineDashboardController.GetStatusAsync() in C:\Projects\CncGeneratorV4\CncGenerator\CncGenerator\MachineDashboard\MachineDashboardController.cs:line 26
   at CncGenerator.Shared.MachineDashboard.OnInitializedAsync() in c:\Projects\CncGeneratorV4\CncGenerator\CncGenerator\Shared\MachineDashboard.razor:line 24
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

So I have found some posts that explain how to set thoses Cors by adding

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsAllowAll",
        builder =>
        {
            builder.AllowAnyMethod()
                .AllowAnyOrigin()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET, PATCH, DELETE, PUT, POST, OPTIONS");
        });
});

And if I understood correctly I should then do

var app = builder.Build();
app.UseCors("CorsAllowAll");
await app.RunAsync();

But I am a bit lost with the new way to do with .net 6 because app return a WebAssemblyHost and not a IApplicationBuilder as expected to be able to use the extension method UseCors.

How could I do to fix it?

Regards,

CodePudding user response:

I need to do a GET on a json that is hosted in a service that I didn't control

When that server is not configured to allow CORS requests then you're out of luck as far as using a SPA client is concerned.

You can call that service from your own Server. So make a pass-through endpoint.

How do I say to chrome then to bypass his default securities?

Lots of hackers would like to know that too.

  • Related