代码之家  ›  专栏  ›  技术社区  ›  Phil

如何从Blazor应用程序调用rest服务

  •  0
  • Phil  · 技术社区  · 6 年前

    在创建一个默认的Blazor应用程序(V0.5.1)之后,我们得到一个获取数据.cshtml从本地.json文件获取数据的页

    @functions {
        WeatherForecast[] forecasts;
    
        protected override async Task OnInitAsync()
        {
            forecasts = await Http.GetJsonAsync<WeatherForecast[]>("sample-data/weather.json");
        }
    
        class WeatherForecast
        {
            public DateTime Date { get; set; }
            public int TemperatureC { get; set; }
            public int TemperatureF { get; set; }
            public string Summary { get; set; }
        }
    }
    

    这个很好用。但是,如果将此更改为从.net core rest web api获取相同的数据,则调用 Http.GetJsonAsync 挂起。没有错误,只是永远不会完成。

        protected override async Task OnInitAsync()
        {
            forecasts = await Http.GetJsonAsync<WeatherForecast[]>(
                "http://localhost:5000/api/weatherforecast/");
        }
    

    我错过了什么?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Flores    6 年前

    很可能您遇到了CORS问题,因为API和站点运行在不同的端口上。

        2
  •  1
  •   Phil    6 年前

    How do you enable cross-origin requests (CORS) in ASP.NET Core MVC . 在默认的web服务代码中添加几行代码就成功了。

            public void ConfigureServices(IServiceCollection services)
            {
                // add this
                services.AddCors(); 
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }
    
    request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                // and this
                app.UseCors(builder =>
                {
                    builder.WithOrigins("http://localhost:5000")
                           .WithMethods("GET", "POST")
                           .AllowAnyHeader();
                });
    
                app.UseMvc();
            }