c# - 我应该使用 AddMvc 还是 AddMvcCore 进行 ASP.NET Core MVC 开发?

标签 c# asp.net-core-mvc

我正在看书学习ASP.NET Core MVC,问题代码片段如下:

// 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() 如下:

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

我在这里做的对吗?

最佳答案

看看 MvcServiceCollectionExtensions.csASP.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() 均返回可用于进一步配置 MVC 服务的 IMvcBuilder

AddMvcCore(),顾名思义,只添加 MVC 管道的核心组件,需要您自己添加任何其他中间件(您的项目需要)。

AddMvc() 在内部调用 AddMvcCore() 并添加其他中间件,例如 Razor View 引擎、Razor 页面、CORS 等。

现在,我会按照您的教程建议并坚持使用 AddMvc()


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

引用this article和 MSDN,了解有关它们的作用以及何时使用它们的更多信息。

关于c# - 我应该使用 AddMvc 还是 AddMvcCore 进行 ASP.NET Core MVC 开发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40097229/

相关文章:

asp.net-core - 什么是遥测配置以及为什么我们在 ASP.NET Core 中使用它?

asp.net-core - 新鲜的 ASP.NET Core 2.0 MVC Web 应用程序模板浏览器链接有效但有 404 错误

c# - 发布 ASP.NET Core Web 应用程序时缺少 DLL

c# - 将日期从 View 传递到 Controller mvc/c#

c# - 基类型的基类型

c# - 检测图何时重新收敛的算法(类似于公共(public)子树?)

c# - 通过 UseUrls 指定监听 HTTP 端口的方式是否正确?

c# - HTTP 错误 310 ERR_TOO_MANY_REDIRECTS 与 RequireHttpsAttribute ASP.NET Core

c# - 创建自定义 NewtonSoft JSON 转换器

c# - 在asp.net 中如何确定用户来自哪里?