首页 新闻 搜索 专区 学院

Webapi + blazor跨域问题

0
悬赏园豆:20 [已解决问题] 解决于 2020-06-22 10:00

报错:

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");

仍然提示这个问题,入门小白,请各位不吝赐教

猝不及防的主页 猝不及防 | 老鸟四级 | 园豆:2493
提问于:2020-06-18 17:32
< >
分享
最佳答案
0

如果我没记错的话,Blazor Client 还没有正式 Release,你用Blazor Server mode就可以不用webAPI调用,直接Native 模式,还快。

收获园豆:20
爱编程的大叔 | 高人七级 |园豆:30753 | 2020-06-19 08:45

大叔我问个问题,打开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...

猝不及防 | 园豆:2493 (老鸟四级) | 2020-06-19 11:51

@猝不及防: 两个端口一样的,只是一个HTTPS,一个HTTP而已。

爱编程的大叔 | 园豆:30753 (高人七级) | 2020-06-19 11:56
其他回答(1)
0

老实说我试了网上几个办法去设置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();
                 
                });
            });
猝不及防 | 园豆:2493 (老鸟四级) | 2020-06-22 10:00
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册