Reputation: 12868
I'm not a big fan of using the pre-bundled AddMvc()
and prefer to use the AddMvcCore()
instead.
Having said that, I was wondering how to go about using the new (as of 2.0) AddRazorPages()
with AddMvcCore()
.
For example, if we do a "bare-bones" configuration of middleware to only use AddRazorPages()
which is found from the official repository
// loaded the NuGet package Microsoft.AspNetCore.Mvc.RazorPages
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddRazorPages();
}
After I created a foo.cshtml
page and placed it into the .\Pages\
directory, it is returning a 404 (Page not found) when I navigate to the URL \Foo
.
.\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>
The sample page above is taken from the 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.
Upvotes: 2
Views: 2123
Reputation: 12868
It turns out there were two issues.
(1) I needed to run the MVC middleware (duh!)
public void Configure(IApplicationBuilder app, ... )
{
app.UseMvc();
}
(2) Then I got an exception thrown, which forced me to have to include .AddAuthorization()
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddRazorPages();
}
Here it is super-simplified into a simple Console app:
//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();
}
Upvotes: 5
Reputation: 119017
Taking a look at the source code for AddMvc
we can see that it calls AddMvcCore
internally and then proceeds to add additional items. So if I were you I would start adding these items in until you get Razor Pages to work, probably focusing on the Razor parts. For example:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddViews()
.AddRazorViewEngine()
.AddRazorPages();
}
Upvotes: 1