我一直试图在Blazor客户端Web程序集中与一起调用单独的asp.net核心Web api。我将模板Web API模板与此控制器一起使用。我在startup.cs中设置了CORS。我在Blazor客户端中使用标准的HTTP客户端。在本地运行,我可以在API代码上设置一个断点,然后看到它被击中。但是客户端抛出异常:类型错误
任何帮助将不胜感激。
David
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
Startup.cs
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
Blazor Client
var response = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
当您使用命名策略时,应通过Configure方法将其添加到CORS中间件中。您的Startup类应类似于以下内容:
注意:我没有更改您的设置。自己动手:不能将AllowAnyOrigin
与WithOrigins
一起使用,彼此取反。
注意:如果您希望Blazor应用程序能够执行启用了CORS的呼叫,请在Web Api端点上添加其URL,并带有WithOrigins
或更好地使用,而根本不使用AllowAnyOrigin
即可使用WithOrigins
。
public class Startup
{
readonly string MyAllowSpecificOrigins = "AllowedOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}
// Add the CORS middleware: app.UseCors(MyAllowSpecificOrigins);
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
希望这有帮助...