简体   繁体   中英

Blazor WASM request has been blocked by CORS policy

I'm currently building a Blazor WebAssembly application, which is displaying data from my ASP.NET Core 6 API. Note, that the projects are seperated in two different solutions.

The problem is that my API rejects the requests, which were send by my WASM application. Apparently that has to do with the CORS configuration of my API.

Access to fetch at 'https://localhost:7030/api/v1/test' from origin 'https://localhost:44338' 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.

The CORS configuration for the API is based on this answer by Aae Que .

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
                builder.WithOrigin("https://localhost:7198")
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                );
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

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

The service class, which is responsible for sending the requests, looks like the following.

public class TestService : ITestService
{
    private readonly HttpClient _httpClient;

    public TestService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> GetTest()
    {
        return await _httpClient.GetFromJsonAsync<string>("test");
    }
}

The above service is implemented in Program.cs .

builder.Services.AddSingleton<TestService>();
builder.Services.AddHttpClient<ITestService, TestService(client =>
{
    client.BaseAddress = new Uri("https://localhost:7030/api/v1/");
});

Does anybody has an idea how I could solve my issue?

I highly appreciate any kind of help, cheers: :)

Step 1 Created a string property not necessary, you can create a field

internal string MySpecificOrigins { get; private set; } = "mySpecificOrigins";

In ConfigureServices Method

Added CORS service like

            services.AddCors(options =>
            {
                options.AddPolicy(name: MySpecificOrigins,
                                  builder =>
                                  {
                                      builder.WithOrigins("https://localhost:7198")
                                      .AllowAnyHeader() 
                                      .AllowAnyMethod()
                                      .AllowCredentials();
                                  });
            });

Then in Configure method used CORS like

app.UseCors(MySpecificOrigins);

and every thing worked fine for me

EDIT CONFIGURATION FOR WEB API Hosted in IIS FOR CORS

AND you need to install CORS module and URLRewrite module in IIS

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="false">
        <remove name="WebDAVModule" />
      </modules>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\YOUR_WebApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
      <cors enabled="true" failUnlistedOrigins="true">
        <add origin="YOUR BLAZOR APP ADDRESS">
          <allowHeaders allowAllRequestedHeaders="true" />
          <allowMethods>
            <add method="GET" />
            <add method="POST" />
            <add method="PUT" />
            <add method="HEAD" />
            <add method="DELETE" />
            <add method="PATCH" />
            <add method="OPTIONS" />
      </allowMethods>
        </add>
        <add origin="http://*" allowed="false" />
      </cors>
    </system.webServer>
  </location>
    <system.web>
        <compilation batch="false" defaultLanguage="c#" />
    </system.web>
</configuration>
<!--ProjectGuid: 6d861e57-65ec-41b9-a702-4e6cc9cad11a-->

AND ALSO YOU HAVE TO DISABLE OR REMOVE WebDAVModule Module

This may be a long shot, but I had similar issue and figured out by specifying concrete HTTP methods:

options.AddDefaultPolicy(builder =>
 builder.WithOrigins("https://localhost:44338")
 .WithMethods("GET", "POST", "PUT", "DELETE")
 .AllowAnyHeader()
);

The CORS configuration of my ASP.NET Core application is totally fine. It was my own fault that it didn't worked. Since I am now starting the Blazor WASM application via IIS, the application runs on https://localhost:44365 instead of https://localhost:7198 . Knowing that, the CORS configuration should look like the following.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
                builder.WithOrigin("https://localhost:44365")
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                );
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

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

Anyways, I want to add some more informations on how to configure CORS, since many of you invested much effort to help me out.

First of all, this is not a complete CORS configuration. Only use this for development purposes , because it's very insecure to quite literally allow every kind of request to your API.

I would also like to reiterate that the order, ie when the CORS are configured, is extremely important . Here you can find more informations about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM