Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ExceptionHandlingMiddleware.cs 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Threading.Tasks;
  8. using Newtonsoft.Json;
  9. using Serilog;
  10. namespace MVCTemplate.Infrastructure.Middleware
  11. {
  12. public class ExceptionHandlingMiddleware
  13. {
  14. private RequestDelegate nextRequestDelegate;
  15. private IWebHostEnvironment environment;
  16. public ExceptionHandlingMiddleware(
  17. RequestDelegate nextRequestDelegate,
  18. IWebHostEnvironment environment
  19. )
  20. {
  21. this.nextRequestDelegate = nextRequestDelegate ?? throw new ArgumentNullException(nameof(nextRequestDelegate));
  22. this.environment = environment ?? throw new ArgumentNullException(nameof(environment));
  23. }
  24. public async Task Invoke(HttpContext context)
  25. {
  26. try
  27. {
  28. context.TraceIdentifier = Guid.NewGuid().ToString();
  29. await this.nextRequestDelegate(context);
  30. }
  31. catch (Exception ex)
  32. {
  33. await this.HandleGlobalExceptionAsync(context, ex);
  34. }
  35. }
  36. private async Task HandleGlobalExceptionAsync(HttpContext context, Exception ex)
  37. {
  38. try
  39. {
  40. await this.WriteResponseAsync(context, HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(ex.Message));
  41. }
  42. catch (Exception e)
  43. {
  44. await this.WriteResponseAsync(context, HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(e.Message));
  45. }
  46. var logger = new LoggerConfiguration()
  47. .MinimumLevel.Debug()
  48. .WriteTo.File(@"AppData\Errors\log-.log", rollingInterval: RollingInterval.Day)
  49. .CreateLogger();
  50. logger.Error(ex, "Unhandled Exception"/* - Detected UserId: {UserId}" /*, context.User.GetUserId()*/);
  51. }
  52. private async Task WriteResponseAsync(HttpContext context, HttpStatusCode code, string jsonResponse)
  53. {
  54. context.Response.ContentType = "application/json";
  55. context.Response.StatusCode = (int)code;
  56. await context.Response.WriteAsync(jsonResponse);
  57. }
  58. }
  59. }