CustomErrorMiddleware.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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.Text;
  7. using System.Threading.Tasks;
  8. using NLog;
  9. using NLog.Web.AspNetCore;
  10. namespace WebAPIBase.Utils
  11. {
  12. public class CustomErrorMiddleware : ICustomErrorMiddleware
  13. {
  14. private readonly RequestDelegate next;
  15. private IHostingEnvironment environment;
  16. //Nlog构造方法注入
  17. private readonly Microsoft.Extensions.Logging.ILogger<CustomErrorMiddleware> _logger;
  18. public CustomErrorMiddleware(RequestDelegate next, IHostingEnvironment environment, Microsoft.Extensions.Logging.ILogger<CustomErrorMiddleware> logger)
  19. {
  20. _logger = logger;
  21. this.next = next;
  22. this.environment = environment;
  23. }
  24. public async Task Invoke(HttpContext context)
  25. {
  26. try
  27. {
  28. await next.Invoke(context);
  29. var features = context.Features;
  30. }
  31. catch (Exception e)
  32. {
  33. await HandleException(context, e);
  34. }
  35. }
  36. private async Task HandleException(HttpContext context, Exception ex)
  37. {
  38. //_logger.Log();
  39. await context.Response.WriteAsync(ex.Message + "\r\n" + ex.StackTrace);
  40. }
  41. public void LogError(Exception ex)
  42. {
  43. // _logger.Log();
  44. }
  45. }
  46. }