Host.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Hosting;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Vit.Extensions;
  6. namespace Vit.WebHost
  7. {
  8. public class Host
  9. {
  10. #region Run
  11. public static void Run(int port = 8888, string rootPath = null, Action<IApplicationBuilder> OnConfigure = null)
  12. {
  13. Run(rootPath, OnConfigure, "http://*:" + port);
  14. }
  15. public static void Run(string rootPath = null, Action<IApplicationBuilder> OnConfigure = null, params string[] urls)
  16. {
  17. Run(new HostRunArg
  18. {
  19. OnConfigure = OnConfigure,
  20. urls = urls,
  21. staticFiles=new StaticFilesConfig { rootPath= rootPath }
  22. });
  23. }
  24. public static void Run(HostRunArg arg)
  25. {
  26. Action<IServiceCollection> OnConfigureServices = null;
  27. Action<IApplicationBuilder> OnConfigure = null;
  28. #region (x.1)允许跨域访问
  29. if (arg.allowAnyOrigin)
  30. {
  31. OnConfigureServices += IServiceCollectionExtensions_AllowAnyOrigin.AllowAnyOrigin_ConfigureServices;
  32. OnConfigure += IServiceCollectionExtensions_AllowAnyOrigin.AllowAnyOrigin_Configure;
  33. }
  34. #endregion
  35. #region (x.2)UseStaticFiles
  36. if (arg.staticFiles != null)
  37. {
  38. OnConfigure += (app) =>
  39. {
  40. app.UseStaticFiles(arg.staticFiles);
  41. };
  42. }
  43. #endregion
  44. #region demo OnConfigure
  45. //OnConfigure += (app) =>{
  46. // app.Use(async (context, next) =>
  47. // {
  48. // await context.Response.WriteAsync("进入第一个委托 执行下一个委托之前\r\n");
  49. // //调用管道中的下一个委托
  50. // await next.Invoke();
  51. // await context.Response.WriteAsync("结束第一个委托 执行下一个委托之后\r\n");
  52. // });
  53. // app.Run(async (context) =>
  54. // {
  55. // await context.Response.WriteAsync("hello, here is from netcore.");
  56. // });
  57. //};
  58. #endregion
  59. #region (x.3) Build host
  60. OnConfigureServices += arg.OnConfigureServices;
  61. OnConfigure += arg.OnConfigure;
  62. var host =
  63. arg.OnCreateWebHostBuilder()
  64. .UseUrls(arg.urls)
  65. .ConfigureServices(OnConfigureServices)
  66. .Configure(OnConfigure)
  67. .Build();
  68. #endregion
  69. #region (x.4) Run
  70. if (arg.RunAsync)
  71. {
  72. host.RunAsync();
  73. }
  74. else
  75. {
  76. host.Run();
  77. }
  78. #endregion
  79. }
  80. #endregion
  81. }
  82. }