如何从Blazor应用程序调用rest服务
创建默认Blazor应用程序V0.5.1后,我们将获得一个FetchData.cshtml页面,该页面从本地.json文件获取数据如何从Blazor应用程序调用rest服务,rest,blazor,Rest,Blazor,创建默认Blazor应用程序V0.5.1后,我们将获得一个FetchData.cshtml页面,该页面从本地.json文件获取数据 @functions { WeatherForecast[] forecasts; protected override async Task OnInitAsync() { forecasts = await Http.GetJsonAsync<WeatherForecast[]>("sample-data/w
@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; }
}
}
我遗漏了什么?很可能您遇到了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();
}
你说得对。检查控制台输出显示“不存在访问控制允许原点标头…”…。将请求的模式设置为no cors以获取禁用cors的资源。Flores让我找到了正确的位置。还有一个错误,我只需要添加一个异常处理程序。但请确保将其添加到Startup.cs以及StartupJavaScript.cs(如果后者存在)。那是我的问题。
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();
}