[英]How to navigate to an ASP.NET Core MVC controller in Blazor app?
[英]MVC controller API access in Blazor not working with .NET Core 3.0
我正在嘗試設置 Blazor 服務器端應用程序,但遇到應用程序從我的 MVC Controller API 讀取數據的問題。 我有一個 controller 用於我的 model 研究,名為 StudyController。 當我啟動 Blazor 應用程序時,我可以訪問我的 GetAll() 路由“/studies”的 json 數據,但 Blazor 應用程序沒有讀取數據。 下面的代碼:
研究控制器:
[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 頁面 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 配置代碼:
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()
並且正確加載了數據。
您可以得到任何異常,例如“提供了無效的請求 URI。請求 URI 必須是絕對 URI 或必須設置 BaseAddress。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.