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; namespace WebAPIBase.Utils { public class CustomErrorMiddleware : ICustomErrorMiddleware { private readonly RequestDelegate next; private IHostingEnvironment environment; //Nlog构造方法注入 private readonly Microsoft.Extensions.Logging.ILogger _logger; public CustomErrorMiddleware(RequestDelegate next, IHostingEnvironment environment, Microsoft.Extensions.Logging.ILogger logger) { _logger = logger; this.next = next; this.environment = environment; } public async Task Invoke(HttpContext context) { try { await next.Invoke(context); var features = context.Features; } catch (Exception e) { await HandleException(context, e); } } private async Task HandleException(HttpContext context, Exception ex) { //_logger.Log(); await context.Response.WriteAsync(ex.Message + "\r\n" + ex.StackTrace); } public void LogError(Exception ex) { // _logger.Log(); } } }