【问题标题】:Different mechanism of HttpClient in Blazor server side and Web assemblyBlazor 服务器端和 Web 程序集中 HttpClient 的不同机制
【发布时间】:2021-02-08 10:03:58
【问题描述】:

我想使用 HttpClient Factory 从 ASP.net Core API 获取数据。 我像这样使用 Microsoft.Extensions.Http 包:

// Register service in IOC containter 
builder.Services.AddHttpClient<IProductService, ProductService>(option =>
                {
                    option.BaseAddress = new Uri(""/*Base url*/);
                });

// Use in service 
var stream = await _httpClient.GetStreamAsync("");

当我在 Blazor 服务器端使用代码并正常工作时。但是当我在 Blazor 中使用代码时会抛出异常

CORS 策略已阻止从源“blazor wasm app url”获取“http client factory base url”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

ASP.net 核心 API 没有变化,结果不同。 我在所有应用程序中使用 .net core 3.1 谢谢

【问题讨论】:

标签: asp.net-core blazor


【解决方案1】:

我像这样在我的 API 中激活 CORS

// In ConfigureServices method
    options.AddPolicy("OpenCors", builder =>
                {
                    builder
                          .AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                      ;
});

// In Configure method
app.UseCors("OpenCors");

                

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2021-10-29
    • 2020-06-09
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多