问题
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