How does AddRazorPages add support for MVC + views?

52 Views Asked by At

I want to use Razor Pages and "MVC with views" simultaneously.

So I used services.AddRazorPages() (which gives RazorPages and WebAPI) and then services.AddControllersWithViews() (which gives MVC and MVC+views).

That works.

But if I omit the latter, it also works. Why?

The source shows that AddRazorPages adds basic WebAPI support via services.AddMvcCore(). However I don't understand how/where mvc+views is added? I want to know whether this is expected behaviour or whether I've made a config mistake.

1

There are 1 best solutions below

6
Brando Zhang On BEST ANSWER

Actually, if you just use the AddMVCCore, it will not register the view service which will make your application not work with the view.

Like below error:

enter image description here

But the services.AddRazorPages will add the RazorViewEngine and it contains the View features which will make the MVC view works.

Source codes of the :

/// <summary>
/// Register services needed for Razor Pages.
/// </summary>
/// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
/// <param name="setupAction">The action to setup the <see cref="RazorPagesOptions"/>.</param>
/// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
public static IMvcCoreBuilder AddRazorPages(
    this IMvcCoreBuilder builder,
    Action<RazorPagesOptions> setupAction)
{
    ArgumentNullException.ThrowIfNull(builder);
    ArgumentNullException.ThrowIfNull(setupAction);

    builder.AddRazorViewEngine();

    AddRazorPagesServices(builder.Services);

    builder.Services.Configure(setupAction);

    return builder;
}

So if you use below codes inside the MVC application it will also work well.

builder.Services.AddMvcCore().AddRazorViewEngine();