如何从 Blazor 应用调用休息服务
How can I call a rest service from a Blazor app
创建默认 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 core rest web api 获取相同的数据,则对 Http.GetJsonAsync
的调用将挂起。没有错误,只是永远不会完成。
protected override async Task OnInitAsync()
{
forecasts = await Http.GetJsonAsync<WeatherForecast[]>(
"http://localhost:5000/api/weatherforecast/");
}
我错过了什么?
您很可能 运行 遇到了 CORS 问题,因为 API 和站点 运行 在不同的端口上。
我需要根据 启用 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();
}
创建默认 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 core rest web api 获取相同的数据,则对 Http.GetJsonAsync
的调用将挂起。没有错误,只是永远不会完成。
protected override async Task OnInitAsync()
{
forecasts = await Http.GetJsonAsync<WeatherForecast[]>(
"http://localhost:5000/api/weatherforecast/");
}
我错过了什么?
您很可能 运行 遇到了 CORS 问题,因为 API 和站点 运行 在不同的端口上。
我需要根据
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();
}