Should I use AddMvc or AddMvcCore for ASP.NET Core MVC development?

假装没事ソ 提交于 2019-12-03 06:11:32

问题


I am learning ASP.NET Core MVC from a book, the code snippet in question is as follows:

// CHAPTER 4 - ESSENTIAL C# FEATURES
namespace LanguageFeatures {

    public class Startup {

        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc();
        }

        // etc.

Because the book is about ASP.NET Core MVC rather than ASP.NET MVC, I think I have to use AddMvcCore() rather than AddMvc() as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore(); // as opposed to:
    //services.AddMvc();
}

Is what I do here correct?


回答1:


Have a look at the MvcServiceCollectionExtensions.cs class on the ASP.NET Core GitHub repo:

public static IMvcBuilder AddMvc(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    var builder = services.AddMvcCore();

    builder.AddApiExplorer();
    builder.AddAuthorization();

    AddDefaultFrameworkParts(builder.PartManager);

    // Order added affects options setup order

    // Default framework order
    builder.AddFormatterMappings();
    builder.AddViews();
    builder.AddRazorViewEngine();
    builder.AddCacheTagHelper();

    // +1 order
    builder.AddDataAnnotations(); // +1 order

    // +10 order
    builder.AddJsonFormatters();

    builder.AddCors();

    return new MvcBuilder(builder.Services, builder.PartManager);
}

AddMvcCore() and AddMvc() both return an IMvcBuilder that can be used to further configure the MVC services.

AddMvcCore(), as the name implies, only adds core components, requiring you to add any other middleware (needed for your project) by yourself.

AddMvc() internally calls AddMvcCore() and adds other middleware such as the Razor view engine, JSON formatters, CORS, etc.

For now, I would follow what your tutorial suggests and stick to AddMvc().



来源:https://stackoverflow.com/questions/40097229/should-i-use-addmvc-or-addmvccore-for-asp-net-core-mvc-development

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!