TimeRestrictionMiddleware.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using Microsoft.AspNetCore.Http;
  2. using NPOI.SS.Formula.Functions;
  3. using System.Text.Encodings.Web;
  4. using System.Text.Json;
  5. using System.Text.Unicode;
  6. namespace OASystem.API.Middlewares
  7. {
  8. /// <summary>
  9. /// 设置时间端访问All接口
  10. /// </summary>
  11. public class TimeRestrictionMiddleware
  12. {
  13. private readonly RequestDelegate _next;
  14. private readonly DateTime _startDateTime;
  15. private readonly DateTime _endDateTime;
  16. public TimeRestrictionMiddleware(RequestDelegate next, DateTime startDateTime, DateTime endDateTime)
  17. {
  18. _next = next;
  19. _startDateTime = startDateTime;
  20. _endDateTime = endDateTime;
  21. }
  22. public async Task InvokeAsync(HttpContext context)
  23. {
  24. var currentDateTime = DateTime.Now;
  25. if (currentDateTime >= _startDateTime && currentDateTime <= _endDateTime)
  26. {
  27. await _next(context);
  28. }
  29. else
  30. {
  31. if (context.Request.Method == "OPTIONS")
  32. {
  33. context.Response.Headers.Add("Access-Control-Allow-Origin", "http://example.com");
  34. context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  35. context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
  36. }
  37. context.Response.ContentType = "application/json";
  38. context.Response.StatusCode = 201;
  39. var response = context.Response;
  40. var errorResponse = new
  41. {
  42. code = 201,
  43. msg = "NO ACCESS!",
  44. data = "",
  45. count = 0
  46. };
  47. await context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(errorResponse));
  48. }
  49. }
  50. }
  51. }