同一项目中的 Razor 页面和 webapi

Gum*_*ear 20 asp.net-core

我在 .net core 3.0 中创建了一个 Web 应用程序(剃刀页面)。然后我向它添加了一个 api 控制器(都来自模板,只需点击几下)。当我运行应用程序时,razor 页面可以工作,但 api 调用返回 404。问题出在哪里,我该如何使其工作?

Rya*_*yan 37

您需要配置您的启动以支持 web api 和属性路由。

services.AddControllers()添加了对控制器和 API 相关功能的支持,但不支持视图或页面。请参阅MVC 服务注册

endpoints.MapControllers如果应用程序使用属性路由,则添加。请参阅迁移 MVC 控制器

结合剃刀页面和 api,如:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
        });

        services.AddRazorPages()
            .AddNewtonsoftJson();
        services.AddControllers()
            .AddNewtonsoftJson();
    }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
     //other middlewares
      app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
        });
    }
Run Code Online (Sandbox Code Playgroud)


Lio*_*ion 7

除了@Ryan 的回答之外,我还必须添加一个带有控制器/动作模式的默认路由。否则没有控制器是可达的,直到我[Route("example")]在它上面设置了一个装饰器。因为我更喜欢像在 MVC 中一样生成基于模式的路由,所以我定义了这样的默认路由Startup.Configure

app.UseEndpoints(endpoints => {
    endpoints.MapRazorPages();
    endpoints.MapControllerRoute("default", "api/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)

有一个名为 的控制器CommunityController,您现在可以在/api/community/index或仅使用简短形式的索引操作,/api/community原因索引被定义为路由中的默认操作。

此外,仍然需要在ConfigureServices方法中添加控制器组件,如@Ryan 所示:

public void ConfigureServices(IServiceCollection services) {
    services.AddRazorPages();
    services.AddControllers();
    // ...
}
Run Code Online (Sandbox Code Playgroud)

使用 ASP.NET Core 3.1 Razor 页面进行测试。