DD.WellWorkover.Cloud/AsbCloudWebApi/Middlewares/RequerstTrackerMiddleware.cs
Фролов fd74ae20a0 CS2-117, CS2-112
Add exception handle middleware.
Move middlawares into separate files.
2021-11-10 17:04:07 +05:00

55 lines
1.9 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Middlewares
{
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 requestLog = new AsbCloudApp.Data.RequestLogDto
{
UserLogin = context.User?.Identity.Name,
UserIp = context.Connection.RemoteIpAddress.ToString(),
RequestMethod = context.Request.Method,
RequestPath = context.Request.Path.Value,
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
{
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;
}
}
}
}