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");
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With