MVC controller API access in Blazor not working with .NET Core 3.0

Viewed 3722

I am trying to setup a Blazor Server side app, but running into an issue with the app reading data from my MVC Controller API. I have a controller for my model Study called StudyController. I can access the json data for my GetAll() route "/studies" when I launch the Blazor app, but the Blazor app is not reading the data. Code below:

StudyController:

[Route("studies")]
[ApiController]
public class StudyController : ControllerBase
{
    private StudyRepository _ourCustomerRespository;

    public StudyController()
    {
        _ourCustomerRespository = new StudyRepository();
    }

    //[Route("Studies")]
    [HttpGet]
    public List<Study> GetAll()
    {
        return _ourCustomerRespository.GetStudies();
    }

}

Razor page function section trying to access data:

@functions {

IList<Study> studies = new List<Study>();

protected async Task OnInitAsync()
{
    HttpClient Http = new HttpClient();
    studies = await Http.GetJsonAsync<List<Study>>("/studies");
}
}

Startup.cs configuration code:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options => options.EnableEndpointRouting = false)
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

        services.AddControllers();

        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseMvcWithDefaultRoute();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }
2 Answers

It appears the issue was that OnInitAsync() no longer works in the latest version of Blazor. I switched to using OnInitializedAsync() and that data loaded correctly.

You Can get any exception like "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."

Related