DD.WellWorkover.Cloud/AsbCloudWebApi/Middlewares/RequerstTrackerMiddleware.cs

57 lines
2.1 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Middlewares
{
2023-05-19 16:51:41 +05:00
public class RequerstTrackerMiddleware
{
private readonly RequestDelegate next;
public RequerstTrackerMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var service = context.RequestServices.GetRequiredService<AsbCloudApp.Services.IRequerstTrackerService>();
var clientIp = context.Request.Headers["X-Real-IP"].FirstOrDefault();
var requestLog = new AsbCloudApp.Data.RequestLogDto
{
2022-12-26 18:03:26 +05:00
UserLogin = context.User.Identity?.Name ?? string.Empty,
UserIp = clientIp ?? context.Connection?.RemoteIpAddress?.ToString(),
RequestMethod = context.Request.Method,
RequestPath = context.Request.Path.Value,
RequestContentLength = context.Request.ContentLength,
Referer = context.Request.Headers["Referer"].ToString(),
};
{
var userIdString = context.User?.FindFirst("id")?.Value;
if (!string.IsNullOrEmpty(userIdString) && int.TryParse(userIdString, out int userId))
requestLog.UserId = userId;
}
var sw = System.Diagnostics.Stopwatch.StartNew();
try
{
2022-12-26 18:03:26 +05:00
await next.Invoke(context);
sw.Stop();
requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds;
requestLog.Status = context.Response.StatusCode;
service.RegisterRequest(requestLog);
}
catch (System.Exception ex)
{
sw.Stop();
requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds;
requestLog.Status = context.Response.StatusCode;
service.RegisterRequestError(requestLog, ex);
throw;
}
}
}
2023-05-19 16:51:41 +05:00
}