我正在看书学习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.cs
在 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()
均返回可用于进一步配置 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/