2024-07-04 11:02:45 +05:00
|
|
|
using Microsoft.AspNetCore.Http;
|
2021-11-10 17:04:07 +05:00
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2023-11-07 14:02:04 +05:00
|
|
|
using System.Linq;
|
2021-11-10 17:04:07 +05:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
namespace AsbCloudWebApi.Middlewares;
|
|
|
|
|
|
|
|
|
|
|
|
public class RequerstTrackerMiddleware
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
private readonly RequestDelegate next;
|
2023-05-19 16:51:41 +05:00
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
public RequerstTrackerMiddleware(RequestDelegate next)
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
this.next = next;
|
|
|
|
}
|
2021-11-10 17:04:07 +05:00
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
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
|
|
|
|
{
|
|
|
|
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(),
|
|
|
|
};
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
var userIdString = context.User?.FindFirst("id")?.Value;
|
|
|
|
if (!string.IsNullOrEmpty(userIdString) && int.TryParse(userIdString, out int userId))
|
|
|
|
requestLog.UserId = userId;
|
2021-11-10 17:04:07 +05:00
|
|
|
}
|
2024-08-19 10:01:07 +05:00
|
|
|
var sw = System.Diagnostics.Stopwatch.StartNew();
|
|
|
|
try
|
|
|
|
{
|
|
|
|
await next.Invoke(context);
|
|
|
|
sw.Stop();
|
|
|
|
requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds;
|
|
|
|
requestLog.Status = context.Response.StatusCode;
|
|
|
|
service.RegisterRequest(requestLog);
|
|
|
|
}
|
|
|
|
catch (System.Exception ex)
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
sw.Stop();
|
|
|
|
requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds;
|
|
|
|
requestLog.Status = context.Response.StatusCode;
|
|
|
|
service.RegisterRequestError(requestLog, ex);
|
|
|
|
throw;
|
2021-11-10 17:04:07 +05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|