【问题标题】:Blazor WebAssembly - HttpClient: Failed to fetchBlazor WebAssembly - HttpClient:无法获取
【发布时间】:2022-08-02 17:37:53
【问题描述】:

初始情况

我目前正在构建一个 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:7198\' 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 配置基于 this answer by Aae Que

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

        services.AddControllers();
    }

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

        app.UseCors();

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

有人知道我如何解决我的问题吗?

我非常感谢任何形式的帮助,干杯! :)


编辑 1

出于兴趣,我将项目重写为 Blazor Server。显然,无论是否使用 API 的 CORS 配置,Blazor 服务器应用程序发送的请求都可以正常工作。

  • 我们看不到\"Cors:Origins\"。您将需要:7198 某处。

标签: asp.net iis blazor httpclient blazor-webassembly


【解决方案1】:

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 模块

【讨论】:

  • 我已经测试了您的解决方案,但仍然遇到相同的错误。
  • 现在试试上面的代码
  • 我以前也这样做过:)
  • api是托管在iis中还是通过visual studio运行?
  • 我已经尝试了两种变体,同样的错误^^