Phil
Phil

Reputation: 43011

How can I call a rest service from a Blazor app

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?

Upvotes: 0

Views: 3066

Answers (2)

Phil
Phil

Reputation: 43011

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

Upvotes: 1

Flores
Flores

Reputation: 8942

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

Upvotes: 0

Related Questions