我应该使用AddMvc或AddMvcCore进行ASP.NET Core MVC开发吗? [英] Should I use AddMvc or AddMvcCore for ASP.NET Core MVC development?

查看:193
本文介绍了我应该使用AddMvc或AddMvcCore进行ASP.NET Core MVC开发吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一本书中学习ASP.NET Core MVC,有问题的代码段如下:

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.

因为这本书是有关ASP.NET Core MVC而不是ASP.NET MVC的,所以我认为我必须使用AddMvcCore()而不是AddMvc(),如下所示:

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();
}

我在这里做的对吗?

推荐答案

看看 ASP.NET Core GitHub存储库:

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()AddMvc()都返回一个IMvcBuilder,可用于进一步配置MVC服务.

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

AddMvcCore()仅添加MVC管道的核心组件,要求您自己添加任何其他中间件(项目所需).

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

AddMvc()内部调用AddMvcCore()并添加其他中间件,例如Razor视图引擎,JSON格式化程序,CORS等.

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

现在,我将按照您的教程的建议继续操作,并坚持使用AddMvc().

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

从ASP.NET Core 3.0开始,还有其他方法可以对应用程序可用的MVC管道的哪些部分进行细粒度控制:

As of ASP.NET Core 3.0, there are additional methods that give fine-grained control over what portions of the MVC pipeline are available to your application:

请参阅

Refer to this article and MSDN for more information about what they do and when to use them.

这篇关于我应该使用AddMvc或AddMvcCore进行ASP.NET Core MVC开发吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆