我正在尝试设置 Blazor 服务器端应用程序,但遇到了应用程序从我的 MVC Controller API 读取数据的问题。我的模型 Study 有一个名为 StudyController 的 Controller 。当我启动 Blazor 应用程序时,我可以访问我的 GetAll() 路由“/studies”的 json 数据,但 Blazor 应用程序未读取数据。代码如下:
学习 Controller :
[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 页面功能部分:
@functions {
IList<Study> studies = new List<Study>();
protected async Task OnInitAsync()
{
HttpClient Http = new HttpClient();
studies = await Http.GetJsonAsync<List<Study>>("/studies");
}
}
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");
});
}
最佳答案
看来问题是 OnInitAsync()
在最新版本的 Blazor 中不再有效。我改用 OnInitializedAsync()
并正确加载了数据。
关于c# - Blazor 中的 MVC Controller API 访问不适用于 .NET Core 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58306305/