CustomExceptionMiddleware类代码 如下:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Logging;
using Nestle.Portal.Utility.Models;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace DuratiMiddlewareonCollectService.
{
///
/// 自定义异常中间件
///
public class CustomExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger
public CustomExceptionMiddleware(RequestDelegate next, ILogger
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
HttpRequest request = httpContext.Request;
Dictionary
errorData.Add("URL", request.Path.ToString());
errorData.Add("Method", request.Method);
if (request.Method.ToLower().Equals("post"))
{
request.EnableRewind();
Stream stream = request.Body;
byte[] buffer = new byte[request.ContentLength.Value];
stream.Read(buffer, 0, buffer.Length);
errorData.Add("Body", Encoding.UTF8.GetString(buffer));
request.Body.Position = 0;
}
else if (request.Method.ToLower().Equals("get"))
{
errorData.Add("Body", request.QueryString.Value);
}
_logger.LogInformation(JsonConvert.SerializeObject(errorData));
await _next(httpContext);
}
catch (Exception ex)
{
HttpRequest request = httpContext.Request;
Dictionary
var trace = new StackTrace(ex, true);
StackFrame frame = trace.GetFrames()[0];
errorData.Add("MethodName", frame?.GetMethod().Name);
errorData.Add("FileLineNumber", frame?.GetFileLineNumber());
errorData.Add("URL", request.Path.ToString());
errorData.Add("Method", request.Method);
if (request.Method.ToLower().Equals("post"))
{
request.EnableRewind();
Stream stream = request.Body;
byte[] buffer = new byte[request.ContentLength.Value];
stream.Read(buffer, 0, buffer.Length);
errorData.Add("Body", Encoding.UTF8.GetString(buffer));
request.Body.Position = 0;
}
else if (request.Method.ToLower().Equals("get"))
{
errorData.Add("Body", request.QueryString.Value);
}
errorData.Add("ErrorInfo", ex.Message);
_logger.LogError(JsonConvert.SerializeObject(errorData));
await HandleExceptionAsync(httpContext, ex);
}
}
private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
{
return httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new ResultMessage
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CustomExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware
}
}
}
Startup类的 Configure 方法代码如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCustomExceptionMiddleware();
app.UseMvc();
}
Program 类代码如下
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup
//发布需要按以下配置
.UseNLog())
nlog.config 代码如下:
autoReload="true"
internalLogLevel="info"
internalLogFile="internal-nlog.txt">