您好,登錄后才能下訂單哦!
這篇文章主要介紹了.net core webapi如何通過中間件獲取請求和響應內容,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
本文主要根據中間件來實現對.net core webapi
中產生的請求和響應數據進行獲取并存入日志文件中;
這里不詳細介紹日志文件的使用。你可以自己接入NLog,log4net,Exceptionless等
創建接口記錄的中間件
using Microliu.Core.Loggers; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ptibro.Partner.API.Extensions { public class RequestResponseLoggingMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; private SortedDictionary<string, object> _data; private Stopwatch _stopwatch; public RequestResponseLoggingMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; _stopwatch = new Stopwatch(); } public async Task Invoke(HttpContext context) { _stopwatch.Restart(); _data = new SortedDictionary<string, object>(); HttpRequest request = context.Request; _data.Add("request.url", request.Path.ToString()); _data.Add("request.headers", request.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList()))); _data.Add("request.method", request.Method); _data.Add("request.executeStartTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); // 獲取請求body內容 if (request.Method.ToLower().Equals("post")) { // 啟用倒帶功能,就可以讓 Request.Body 可以再次讀取 request.EnableRewind(); Stream stream = request.Body; byte[] buffer = new byte[request.ContentLength.Value]; stream.Read(buffer, 0, buffer.Length); _data.Add("request.body", Encoding.UTF8.GetString(buffer)); request.Body.Position = 0; } else if (request.Method.ToLower().Equals("get")) { _data.Add("request.body", request.QueryString.Value); } // 獲取Response.Body內容 var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; await _next(context); _data.Add("response.body", await GetResponse(context.Response)); _data.Add("response.executeEndTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); await responseBody.CopyToAsync(originalBodyStream); } // 響應完成記錄時間和存入日志 context.Response.OnCompleted(() => { _stopwatch.Stop(); _data.Add("elaspedTime", _stopwatch.ElapsedMilliseconds + "ms"); var json = JsonConvert.SerializeObject(_data); _logger.Debug(json, "api", request.Method.ToUpper()); return Task.CompletedTask; }); } /// <summary> /// 獲取響應內容 /// </summary> /// <param name="response"></param> /// <returns></returns> public async Task<string> GetResponse(HttpResponse response) { response.Body.Seek(0, SeekOrigin.Begin); var text = await new StreamReader(response.Body).ReadToEndAsync(); response.Body.Seek(0, SeekOrigin.Begin); return text; } } /// <summary> /// 擴展中間件 /// </summary> public static class RequestResponseLoggingMiddlewareExtensions { public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder app) { return app.UseMiddleware<RequestResponseLoggingMiddleware>(); } } }
在startup.cs中Configure方法中使用中間件
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseErrorHandling();// 全局異常盡量放上面 ... app.UseRequestResponseLogging(); ... app.UseExceptionless(Configuration); app.UseMvc(); }
現在請求一次看一下記錄的效果:我的日志存在exceptionless上,如下圖
解析json,記錄的數據如下:
感謝你能夠認真閱讀完這篇文章,希望小編分享的“.net core webapi如何通過中間件獲取請求和響應內容”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。