ASP.NET Core 2.0 Razor Pages 使用 AddMvcCore() 而不是 AddMvc()

ASP.NET Core 2.0 Razor Pages using AddMvcCore() instead of AddMvc()

我不太喜欢使用预捆绑的 AddMvc(),我更喜欢使用 AddMvcCore()

话虽如此,我想知道如何使用新的(从 2.0 开始)AddRazorPages()AddMvcCore()

例如,如果我们对中间件进行 "bare-bones" 配置,只使用从 official repository

中找到的 AddRazorPages()
// loaded the NuGet package Microsoft.AspNetCore.Mvc.RazorPages
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
        .AddRazorPages();
}

在我创建 foo.cshtml 页面并将其放入 .\Pages\ 目录后,当我导航到 URL [=20] 时,它返回 404(找不到页面) =].

.\Pages\Foo.cshtml

@page
@model IndexModel
@using Microsoft.AspNetCore.Mvc.RazorPages

@functions {
    public class IndexModel : PageModel
    {
        public string Message { get; private set; } = "In page model: ";

        public void OnGet()
        {
            Message += $" Server seconds  { DateTime.Now.Second.ToString() }";
        }
    }
}

<h2>Hello World</h2>
<p>
    @Model.Message
</p>

上面的示例页面取自Microsoft Documents: Introduction to Razor Pages in ASP.NET Core

Has anyone figured this out, or know what is missing? I'm thinking there is an issue with the routing.

看看 source code for AddMvc 我们可以看到它在内部调用 AddMvcCore 然后继续添加其他项目。因此,如果我是你,我会开始添加这些项目,直到你让 Razor Pages 开始工作,可能会专注于 Razor 部分。例如:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
        .AddViews()
        .AddRazorViewEngine()
        .AddRazorPages();
}

原来有两个问题。

(1) 我需要 运行 MVC 中间件(呃!)

public void Configure(IApplicationBuilder app, ... )
{
    app.UseMvc();
}

(2) 然后我抛出一个异常,这迫使我必须包含 .AddAuthorization()

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
        .AddAuthorization()
        .AddRazorPages();
}

在这里它被超级简化为一个简单的控制台应用程序:

//using System.IO;
//using Microsoft.AspNetCore.Builder;
//using Microsoft.AspNetCore.Hosting;
//using Microsoft.Extensions.DependencyInjection;

public static void Main(string[] args)
{
    IWebHost host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureServices(services =>
        {
            services.AddMvcCore()
                .AddAuthorization()
                .AddRazorPages();
        })
        .Configure(app =>
        {
            //app.UseExceptionHandler("/error");
            app.UseStaticFiles();
            app.UseMvc();
        })
        .Build();

    host.Run();
}