DynamicApiExtens.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Infrastructure.Helper;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.Mvc.ApplicationParts;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Newtonsoft.Json.Converters;
  6. using Newtonsoft.Json.Serialization;
  7. using System.Linq;
  8. using System.Reflection;
  9. namespace ZR.Common.DynamicApiSimple.Extens
  10. {
  11. public static class DynamicApiExtens
  12. {
  13. public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
  14. /// <summary>
  15. /// 注入动态api
  16. /// </summary>
  17. /// <param name="services"></param>
  18. /// <returns></returns>
  19. public static IServiceCollection AddDynamicApi(this IServiceCollection services)
  20. {
  21. services.AddMvc()
  22. .ConfigureApplicationPartManager(m =>
  23. {
  24. foreach (Assembly assembly in AssemblyUtils.GetAssemblies())
  25. {
  26. if (m.ApplicationParts.Any(it => it.Name.Equals(assembly.FullName.Split(',')[0]))) continue;
  27. m.ApplicationParts.Add(new AssemblyPart(assembly));
  28. }
  29. m.FeatureProviders.Add(new ApiFeatureProvider());
  30. }).AddNewtonsoftJson(options =>
  31. {
  32. options.SerializerSettings.DateFormatString = TIME_FORMAT_FULL;
  33. options.SerializerSettings.Converters.Add(new IsoDateTimeConverter
  34. {
  35. DateTimeFormat = TIME_FORMAT_FULL,
  36. });
  37. // 设置为驼峰命名
  38. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  39. });
  40. services.Configure<MvcOptions>(o =>
  41. {
  42. o.Conventions.Add(new ApiConvention());
  43. });
  44. return services;
  45. }
  46. }
  47. }