0

After creating a default Blazor app (V0.5.1) we get a FetchData.cshtml page which gets its data from a local .json file

@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; }
    }
}

This works fine. However, if change this to get the same data from a .net core rest web api the call to Http.GetJsonAsync hangs. There's no error it just never completes.

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

What am I missing?

Phil
  • 42,255
  • 9
  • 100
  • 100

2 Answers2

1

I needed to enable Cors, as per How do you enable cross-origin requests (CORS) in ASP.NET Core MVC. Adding a couple of lines to the default web service code did the trick.

        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();
        }
Phil
  • 42,255
  • 9
  • 100
  • 100
0

Most probably you are running into a CORS issue, because the API and the site are running on a different port.

Flores
  • 8,226
  • 5
  • 49
  • 81
  • you are correct. Inspecting the console output shows 'no "access-control-allow-origin" header is present …. set the request's mode to no-cors to fetch the resource with CORS disabled'. – Phil Sep 09 '18 at 12:27