报错:
Access to fetch at 'https://localhost:5001/api/Devices' from origin 'https://localhost:44387' 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中代码:
protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
devices = await Http.GetFromJsonAsync<Device[]>(ServiceEndpoint);
}
尝试:
在blazor.server中设置:
services.AddCors(options =>
{
options.AddPolicy(name:"xcsd", policyBuilder =>
{
policyBuilder.AllowAnyOrigin();
});
});
app.UseCors("xcsd");
仍然提示这个问题,入门小白,请各位不吝赐教
如果我没记错的话,Blazor Client 还没有正式 Release,你用Blazor Server mode就可以不用webAPI调用,直接Native 模式,还快。
大叔我问个问题,打开web api他会打开两个端口,
其中一个可以post,get啥的,另一个端口是干啥的
比如下面的5000
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: D:\MyCode\Github2020\WebAPI_Test\WebApplication1\WebApplication1
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
@猝不及防: 两个端口一样的,只是一个HTTPS,一个HTTP而已。
老实说我试了网上几个办法去设置webapi跨域,开始反正一直不行,后来莫名其妙的就行了:
Blazor
builder.Services.AddHttpClient("ServerAPI", client =>
{
client.BaseAddress = new Uri(@"https://localhost:5001");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
@code
var client = ClientFactory.CreateClient("ServerAPI");
Webapi
//添加cors 服务 配置跨域处理
services.AddCors(options =>
{
options.AddPolicy("any", builder =>
{
builder.AllowAnyOrigin() //允许任何来源的主机访问
.AllowAnyMethod()
.AllowAnyHeader();
});
});