[英]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.我正在尝试设置 Blazor 服务器端应用程序,但遇到应用程序从我的 MVC Controller API 读取数据的问题。 I have a controller for my model Study called StudyController.
我有一个 controller 用于我的 model 研究,名为 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.
当我启动 Blazor 应用程序时,我可以访问我的 GetAll() 路由“/studies”的 json 数据,但 Blazor 应用程序没有读取数据。 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: Razor 页面 function 部分试图访问数据:
@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: Startup.cs 配置代码:
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.看来问题是
OnInitAsync()
不再适用于最新版本的 Blazor。 I switched to using OnInitializedAsync()
and that data loaded correctly.我切换到使用
OnInitializedAsync()
并且正确加载了数据。
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."您可以得到任何异常,例如“提供了无效的请求 URI。请求 URI 必须是绝对 URI 或必须设置 BaseAddress。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.