這篇文章主要介紹了.net core webapi如何通過(guò)中間件獲取請(qǐng)求和響應(yīng)內(nèi)容,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、重慶小程序開(kāi)發(fā)公司、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了城關(guān)免費(fè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_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 (); 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; }); } /// /// 獲取響應(yīng)內(nèi)容 /// /// ///public async Task 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; } } /// /// 擴(kuò)展中間件 /// public static class RequestResponseLoggingMiddlewareExtensions { public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder app) { return app.UseMiddleware(); } } }
在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ù)如下:
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“.net core webapi如何通過(guò)中間件獲取請(qǐng)求和響應(yīng)內(nèi)容”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,,關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!