【问题标题】:How can I call a rest service from a Blazor app如何从 Blazor 应用调用休息服务
【发布时间】:2019-02-13 23:42:01
【问题描述】:

在创建默认 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 核心 rest web api 获取相同的数据,则对 Http.GetJsonAsync 的调用将挂起。没有错误,只是永远不会完成。

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

我错过了什么?

【问题讨论】:

  • 弗洛雷斯让我找对了地方。
  • 还有一个错误,我只需要添加一个异常处理程序。

标签: rest blazor


【解决方案1】:

根据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();
        }

【讨论】:

  • 但请确保将其添加到 Startup.cs 以及 StartupJavaScript.cs(如果后者也存在)。那是我的问题。
【解决方案2】:

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

【讨论】:

  • 你是对的。检查控制台输出显示“不存在“access-control-allow-origin”标头……。将请求的模式设置为 no-cors 以获取禁用 CORS 的资源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2016-04-02
  • 2018-10-20
  • 2011-08-10
  • 1970-01-01
  • 2016-12-31
相关资源
最近更新 更多