.net core webapi通過(guò)中間件獲取請(qǐng)求和響應(yīng)內(nèi)容的方法
本文主要根據(jù)中間件來(lái)實(shí)現(xiàn)對(duì).net core webapi
中產(chǎn)生的請(qǐng)求和響應(yīng)數(shù)據(jù)進(jìn)行獲取并存入日志文件中;
這里不詳細(xì)介紹日志文件的使用。你可以自己接入NLog,log4net,Exceptionless等
創(chuàng)建接口記錄的中間件
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")); // 獲取請(qǐng)求body內(nèi)容 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內(nèi)容 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); } // 響應(yīng)完成記錄時(shí)間和存入日志 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> /// 獲取響應(yīng)內(nèi)容 /// </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> /// 擴(kuò)展中間件 /// </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(); }
現(xiàn)在請(qǐng)求一次看一下記錄的效果:我的日志存在exceptionless上,如下圖
解析json,記錄的數(shù)據(jù)如下:
總結(jié)
以上所述是小編給大家介紹的.net core webapi通過(guò)中間件獲取請(qǐng)求和響應(yīng)內(nèi)容的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
關(guān)于.net(C#)中的跨進(jìn)程訪問(wèn)的問(wèn)題
C# 跨進(jìn)程訪問(wèn)實(shí)現(xiàn)代碼。2009-04-04asp.net(c#)獲取內(nèi)容第一張圖片地址的函數(shù)
C#獲取文章類第一張圖片的地址的函數(shù)(留著以后用),先說(shuō)一下思路2009-11-11asp.net mvc CodeFirst模式數(shù)據(jù)庫(kù)遷移步驟詳解
這篇文章主要為大家詳細(xì)介紹了asp.net mvc CodeFirst模式數(shù)據(jù)庫(kù)遷移步驟,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10asp.net下GDI+的一些常用應(yīng)用(水印,文字,圓角處理)技巧
asp.net下GDI+的一些常用應(yīng)用(水印,文字,圓角處理)技巧...2007-03-03ASP.NET 統(tǒng)計(jì)圖表控件小結(jié)
近來(lái)客戶需要將前段時(shí)間開(kāi)發(fā)的統(tǒng)計(jì)信息用圖表展示出來(lái),還要多個(gè)圖表類型,例如:柱狀圖、餅圖、曲線圖、三維圖等等。在網(wǎng)上google了一下,發(fā)現(xiàn)了三個(gè)(也許更多)可以使用的控件。下面我們一起看看這三個(gè)控件。2009-11-11ASP.NET實(shí)現(xiàn)數(shù)據(jù)的添加(第10節(jié))
這篇文章主要介紹了ASP.NET如何實(shí)現(xiàn)數(shù)據(jù)的添加,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-08-08