How can I call a rest service from a Blazor app

blazor rest

Question

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?

Accepted Answer

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


Popular Answer

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


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why