繁体   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