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

查看:11
本文介绍了我应该使用 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();
}

我在这里做的正确吗?

推荐答案

看看MvcServiceCollectionExtensions.cs 类 rel="nofollow noreferrer">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.AddRazorPages();
    builder.AddCacheTagHelper();

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

    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 视图引擎、Razor 页面、CORS 等.

AddMvc() internally calls AddMvcCore() and adds other middleware such as the Razor view engine, Razor pages, 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, e.g.:

参考 这篇文章 和 MSDN 了解有关它们的作用以及何时使用它们的更多信息.

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天全站免登陆