CustomErrorMiddleware.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. using System.Net;
  11. using Newtonsoft.Json;
  12. using Microsoft.AspNetCore.Builder;
  13. namespace WebAPIBase.Utils
  14. {
  15. public class CustomErrorMiddleware
  16. {
  17. private readonly RequestDelegate _next;
  18. private static Logger logger = LogManager.GetCurrentClassLogger();
  19. public CustomErrorMiddleware(RequestDelegate next)
  20. {
  21. _next = next;
  22. }
  23. public async Task Invoke(HttpContext httpContext)
  24. {
  25. try
  26. {
  27. await _next(httpContext);
  28. }
  29. catch (Exception ex)
  30. {
  31. logger.Error(ex);
  32. httpContext.Response.StatusCode = 200;
  33. var result = JsonConvert.SerializeObject(new ApiResponse { IsSuccess = false, ErrMsg = ex.Message + "\r\n" + ex.StackTrace, Code = 500 });
  34. httpContext.Response.ContentType = "application/json; charset=utf-8";
  35. await httpContext.Response.WriteAsync(result);
  36. //throw;
  37. }
  38. }
  39. }
  40. // Extension method used to add the middleware to the HTTP request pipeline.
  41. public static class CustomErrorMiddlewareExtensions
  42. {
  43. public static IApplicationBuilder UseCustomErrorMiddleware(this IApplicationBuilder builder)
  44. {
  45. return builder.UseMiddleware<CustomErrorMiddleware>();
  46. }
  47. }
  48. }