Host.cs 3.3 KB

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