服务不包含用于解决 WASM 中的跨站点源问题的 AddCors 的定义

Services does not contain a definition for AddCors for solve Cross site origin problem in WASM

我想从web api中获取一些数据,我写了这段代码:

var response = await Client.GetAsync("https://SomeURL/Action");

当我 运行 单击按钮中的这段代码时,我得到了这个错误:

Access to fetch at 'https://SomeURL/Action' from origin 'http://OtherURL' has been blocked by CORS policy: 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.

所以为了解决这个问题,我试图在 Blazor 应用程序的 program.cs 中添加此代码:

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("https://SomeURL/")
           .AllowAnyHeader()
           .AllowAnyMethod()
           .AllowCredentials()
           .SetIsOriginAllowed((host) => true));
});

Services 不包含 AddCors 的定义。我该如何解决这个问题?谢谢


编辑 1)

我创建了非常简单的内置网站api:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

我得到了结果:

当我想连接到这个网站时 api 我收到 CORS 错误。我在 Web API 项目中更改 program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => 
               builder.WithOrigins("http://localhost:5179")
       .AllowAnyHeader()
       .AllowAnyMethod()
       .AllowCredentials()
       .SetIsOriginAllowed((host) => true));
});

var app = builder.Build();

app.UseCors();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Blazor 项目中我有这个:

@page "/counter"
@inject HttpClient Client

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private async Task IncrementCount()
    {
        currentCount++;

        var response = await Client.GetAsync("https://localhost:7229/weatherforecast");
    }
}

请帮我解决问题。

这对我有用:

以这种方式添加 app.UseCors(); 和策略名称:

app.UseHttpsRedirection();

app.UseCors("CorsPolicy");

app.UseAuthorization();