Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
        });
    }
like image 363
nxvk919 Avatar asked Nov 07 '22 13:11

nxvk919


1 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.

like image 125
nxvk919 Avatar answered Nov 09 '22 22:11

nxvk919