c# – ASP.Net核心Web API捕获日志记录的HTTP请求
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – ASP.Net核心Web API捕获日志记录的HTTP请求,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2390字,纯文字阅读大概需要4分钟。
内容图文
![c# – ASP.Net核心Web API捕获日志记录的HTTP请求](/upload/InfoBanner/zyjiaocheng/805/b8c6589d12ef4452ae8611ebd7f3bc89.jpg)
我在ASP.NET Core Web API中捕获HTTP请求以进行日志记录时遇到困难.我能在这里找到一个例子
http://dotnetliberty.com/index.php/2016/01/07/logging-asp-net-5-requests-using-middleware/
哪有帮助.它基本上是一个使用中间件功能添加到HTTP请求管道的日志类.问题是只在应用程序启动时调用类方法.我无法在我的任何获取或发布http请求上调用它. get或post http请求正在运行,因为我可以调试并且响应正常,我尝试在控制台应用程序中使用Fiddler和http客户端.
这是我的日志记录类
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace CoreWebAPI.Models
{
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
var startTime = DateTime.UtcNow;
var watch = Stopwatch.StartNew();
await _next.Invoke(context);
watch.Stop();
var logTemplate = @"
Client IP: {clientIP}
Request path: {requestPath}
Request content type: {requestContentType}
Request content length: {requestContentLength}
Start time: {startTime}
Duration: {duration}";
_logger.LogInformation(logTemplate,
context.Connection.RemoteIpAddress.ToString(),
context.Request.Path,
context.Request.ContentType,
context.Request.ContentLength,
startTime,
watch.ElapsedMilliseconds);
}
}
}
这是我的Startup.cs类中的Startup.Configure方法
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
app.UseCors(builder => builder.AllowAnyOrigin());
app.UseMiddleware<RequestLoggingMiddleware>();
}
最后一行是使用app.UseMiddleware重新登录HTTP请求的地方.我认为这应该有用,但如果有人知道为什么它没有,或者另一种选择那么好.如果您需要我提供更多信息,请告诉我.
解决方法:
中间件按照它们注册的顺序在一个管道中调用,它们都决定是否应该调用下一个(参见你自己的日志记录中间件:await _next.Invoke(context);).
当一个请求进入由Mvc框架处理时,它将不会传递给下一个中间件.
要记录所有请求,您需要在终止管道的任何中间件(例如Mvc)之前注册日志记录.
内容总结
以上是互联网集市为您收集整理的c# – ASP.Net核心Web API捕获日志记录的HTTP请求全部内容,希望文章能够帮你解决c# – ASP.Net核心Web API捕获日志记录的HTTP请求所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。