52ABP

AddMvc 源码

GitHub:Microsoft.AspNetCore.Mvc/MvcServiceCollectionExtensions.cs

  1. /// <summary>
  2. /// Adds MVC services to the specified <see cref="IServiceCollection" />.
  3. /// </summary>
  4. /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
  5. /// <returns>An <see cref="IMvcBuilder"/> that can be used to further configure the MVC services.</returns>
  6. public static IMvcBuilder AddMvc(this IServiceCollection services)
  7. {
  8. if (services == null)
  9. {
  10. throw new ArgumentNullException(nameof(services));
  11. }
  12. var builder = services.AddMvcCore();
  13. builder.AddApiExplorer();
  14. builder.AddAuthorization();
  15. AddDefaultFrameworkParts(builder.PartManager);
  16. // Order added affects options setup order
  17. // Default framework order
  18. builder.AddFormatterMappings();
  19. builder.AddViews();
  20. builder.AddRazorViewEngine();
  21. builder.AddRazorPages();
  22. builder.AddCacheTagHelper();
  23. // +1 order
  24. builder.AddDataAnnotations(); // +1 order
  25. // +10 order
  26. builder.AddJsonFormatters();
  27. builder.AddCors();
  28. return new MvcBuilder(builder.Services, builder.PartManager);
  29. }

注:参考源码,如下配置就能在 AddMvcCore 时支持 JsonFormatters 了。

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddMvcCore().AddJsonFormatters();
  4. }