c# - Blazor 中的 MVC Controller API 访问不适用于 .NET Core 3.0

标签 c# blazor .net-core-3.0 blazor-server-side asp.net-core-3.0

我正在尝试设置 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/

相关文章:

json - .Net Core 3 和 EF Core 3 包含问题 (JsonException)

c# - EF 迁移显示空的 Up() Down() 方法

redux - Blazor 中的状态管理选项

c# - 无法翻译 LINQ 表达式,将对其求值

c# - 默认 Blazor PWA 项目无法托管到 IIS 中

c# - Blazor 中的 Razor View 引擎(在运行时将 blazor 组件转换为 html 字符串)

c# - 泛型和可空(类与结构)

c# - 按角色获取 ASP.NET Identity 用户

c# - 我的函数使用多少字节? (C#)

c# - 如何获得不同的列表?