Host.cs 3.1 KB

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