123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using NLog;
- using NLog.Web.AspNetCore;
- using System.Net;
- using Newtonsoft.Json;
- using Microsoft.AspNetCore.Builder;
- namespace Utils
- {
- public class CustomErrorMiddleware
- {
- private readonly RequestDelegate _next;
- private static Logger logger = LogManager.GetCurrentClassLogger();
- public CustomErrorMiddleware(RequestDelegate next)
- {
- _next = next;
- }
- public async Task Invoke(HttpContext httpContext)
- {
- try
- {
- await _next(httpContext);
- }
- catch (Exception ex)
- {
- logger.Error(ex);
- httpContext.Response.StatusCode = 200;
- var result = JsonConvert.SerializeObject(new ApiResponse { IsSuccess = false, ErrMsg = ex.Message + "\r\n" + ex.StackTrace, Code = 500 });
- httpContext.Response.ContentType = "application/json; charset=utf-8";
- await httpContext.Response.WriteAsync(result);
- //throw;
- }
- }
- }
- // Extension method used to add the middleware to the HTTP request pipeline.
- public static class CustomErrorMiddlewareExtensions
- {
- public static IApplicationBuilder UseCustomErrorMiddleware(this IApplicationBuilder builder)
- {
- return builder.UseMiddleware<CustomErrorMiddleware>();
- }
- }
- }
|