如何从Blazor应用程序调用休息服务

问题描述 投票:0回答:2

在创建默认的Blazor应用程序(V0.5.1)后,我们得到一个FetchData.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核心休息web api获取相同的数据,则调用Http.GetJsonAsync会挂起。没有错误,它永远不会完成。

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

我错过了什么?

rest blazor
2个回答
0
投票

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


0
投票

根据How do you enable cross-origin requests (CORS) in ASP.NET Core MVC,我需要启用Cors。向默认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();
        }
© www.soinside.com 2019 - 2024. All rights reserved.