Host.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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 += (services) =>
  34. {
  35. services.AddCors();
  36. };
  37. OnConfigure += (app) =>
  38. {
  39. //支持 net core 5.0及以上版本
  40. //https://blog.csdn.net/Jack_Law/article/details/105212759
  41. app.UseCors(builder => builder
  42. //.AllowAnyOrigin()
  43. .SetIsOriginAllowed(_ => true)
  44. .AllowAnyMethod()
  45. .AllowAnyHeader()
  46. .AllowCredentials());
  47. };
  48. }
  49. #endregion
  50. #region (x.2)UseStaticFiles
  51. if (arg.staticFiles != null)
  52. {
  53. OnConfigure += (app) =>
  54. {
  55. app.UseStaticFiles(arg.staticFiles);
  56. };
  57. }
  58. #endregion
  59. #region demo OnConfigure
  60. //OnConfigure += (app) =>{
  61. // app.Use(async (context, next) =>
  62. // {
  63. // await context.Response.WriteAsync("进入第一个委托 执行下一个委托之前\r\n");
  64. // //调用管道中的下一个委托
  65. // await next.Invoke();
  66. // await context.Response.WriteAsync("结束第一个委托 执行下一个委托之后\r\n");
  67. // });
  68. // app.Run(async (context) =>
  69. // {
  70. // await context.Response.WriteAsync("hello, here is from netcore.");
  71. // });
  72. //};
  73. #endregion
  74. #region (x.3) Build host
  75. OnConfigureServices += arg.OnConfigureServices;
  76. OnConfigure += arg.OnConfigure;
  77. var host =
  78. arg.OnCreateWebHostBuilder()
  79. .UseUrls(arg.urls)
  80. .ConfigureServices(OnConfigureServices)
  81. .Configure(OnConfigure)
  82. .Build();
  83. #endregion
  84. #region (x.4) Run
  85. if (arg.RunAsync)
  86. {
  87. host.RunAsync();
  88. }
  89. else
  90. {
  91. host.Run();
  92. }
  93. #endregion
  94. }
  95. #endregion
  96. }
  97. }