Cors issue with Blazor webassembly standalone client

2.4k views Asked by At

I am struggling with some cors issue for DELETE and POST.

GET works fine.

Setup is: .Net core API in Azure API Management and Blazor webassembly standalone client (Azure app service) that calls the API.

Error I get when try to DELETE is.

"has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present"

So I find it difficult to understand what code that is needed here. It is so many example everywhere on CORS for .net core and also the different Blazor setups (server, hosted wasm etc).

I guess I need to handle the preflight request in some way for this to work?

This is what I use right now:

My ServiceTimes.razor that calls the API

@code {

private const string ServiceEndpoint = "https://MyProdAPI.azure-api.net/api/ServiceTimes";
private LWS_ServiceTimes[] servicetimes;



LWS_ServiceTimes servicetimeObj = new LWS_ServiceTimes();

string ids = "0";
bool showAddrow = false;

bool loadFailed;

protected override async Task OnInitializedAsync()
{
    ids = "0";
    try
    {
        servicetimes = await Http.GetFromJsonAsync<LWS_ServiceTimes[]>(ServiceEndpoint);
    }
    catch (AccessTokenNotAvailableException exception)
    {
        exception.Redirect();
    }
}


// Delete Method
protected async Task DeleteServiceTimes(long ServiceTimesID)
{
    showAddrow = false;

    ids = ServiceTimesID.ToString();
    await Http.DeleteAsync("https://MyprodAPI.azure-api.net/api/ServiceTimes/1"); //Deletes the ID=1

 }

Blazor webassembly standalone client Program.cs

 public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");

        builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://prodsite.azurewebsites.net") });

        builder.Services.AddMsalAuthentication(options =>
        {
            builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
            options.ProviderOptions.DefaultAccessTokenScopes.Add("api://xxxxxxxx-xxxx-xxxx-xxxx-xxxx/API.Access"); //API.Acess my scope in API
        });

        builder.Services.AddHttpClient("ServerAPI",
    client => client.BaseAddress = new Uri("https://MyprodAPI.azure-api.net"))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

        builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
            .CreateClient("ServerAPI"));

        await builder.Build().RunAsync();
    }

API Startup

public void ConfigureServices(IServiceCollection services)
    {
        
        services.AddDbContext<LwsSpiderContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDatabase")));

        services.AddSwaggerGen();

      

         services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("https://prodsite.azurewebsites.net");
                                 builder.AllowAnyMethod();
                                builder.WithHeaders(HeaderNames.ContentType, HeaderNames.Authorization, "x-custom-header");
                                  builder.AllowCredentials();
        });
        });
        services.AddControllers();
        
      }

   
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseSwagger();

       // app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("MyAllowSpecificOrigins");

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    
    }
0

There are 0 answers