簡體   English   中英

Blazor WASM 請求已被 CORS 策略阻止

[英]Blazor WASM request has been blocked by CORS policy

我目前正在構建一個 Blazor WebAssembly 應用程序,它顯示來自我的 ASP.NET Core 6 API 的數據。 請注意,這些項目分為兩種不同的解決方案。

問題是我的 API 拒絕了我的 WASM 應用程序發送的請求。 顯然這與我的 API 的 CORS 配置有關。

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.

API 的 CORS 配置基於 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();
        });
    }
}

負責發送請求的服務 class 如下所示。

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");
    }
}

上述服務在Program.cs中實現。

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

有人知道我如何解決我的問題嗎?

我非常感謝任何形式的幫助,干杯::)

Step 1 創建字符串屬性不是必須的,你可以創建一個字段

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

在 ConfigureServices 方法中

添加了 CORS 服務,例如

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

然后在配置方法中使用 CORS

app.UseCors(MySpecificOrigins);

一切對我來說都很好

為 CORS 托管在 IIS 中的 WEB API 編輯配置

並且您需要在 IIS 中安裝 CORS 模塊和 URLRewrite 模塊

<?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-->

並且您還必須禁用或刪除 WebDAVModule 模塊

這可能是一個長鏡頭,但我有類似的問題,並通過指定具體的 HTTP 方法來解決:

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

我的 ASP.NET 核心應用程序的 CORS 配置完全沒問題。 它沒有奏效是我自己的錯。 Since I am now starting the Blazor WASM application via IIS, the application runs on https://localhost:44365 instead of https://localhost:7198 . 知道了這一點,CORS 配置應該如下所示。

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();
        });
    }
}

無論如何,我想添加一些關於如何配置 CORS 的更多信息,因為你們中的許多人都付出了很多努力來幫助我。

首先,這不是一個完整的 CORS 配置。 僅將其用於開發目的,因為從字面上允許對 API 的各種請求是非常不安全的

我還想重申,配置 CORS 時的順序非常重要 在這里您可以找到有關它的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM