Home > OS >  Intercepting HttpRequest and log contents to a database
Intercepting HttpRequest and log contents to a database

Time:12-12

I would like to intercept all Httprequest and log the contents to a database table. I am using EF core, swagger and c# in vs. I would also like to add a background worker that deletes this requests every seven days.

I have tried using RequestDelegate but I am not able to save the information to a database

CodePudding user response:

Your question is a bit too broad to fit this forum, but here's an example of the first part at least - a request logger that saves uri and body of a request to a database table;

public class RequestMessageLogger : IRequestMessageLogger
{
    private readonly MyDbContext _dbContext;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public RequestMessageLogger(MyDbContext dbContext, IHttpContextAccessor httpContextAccessor)
    {
        _dbContext = dbContext;
        _httpContextAccessor = httpContextAccessor;
    }

    public void LogRequest()
    {
        string bodyAsString = null;
        if (_httpContextAccessor.HttpContext.Request.Body.CanSeek)
        {
            RewindStream();

            using StreamReader reader = new StreamReader(_httpContextAccessor.HttpContext.Request.Body, Encoding.UTF8, true, 1024, true);
            bodyAsString = reader.ReadToEnd();

            RewindStream();
        }
            
        var uri = _httpContextAccessor.HttpContext.Request.GetDisplayUrl();

        _dbContext.RequestMessages.Add(new RequestMessage { Message = bodyAsString, Received = DateTime.Now, Uri = uri });

        _dbContext.SaveChanges();
    }

    private void RewindStream() => _httpContextAccessor.HttpContext.Request.Body.Position = 0;
}

Just inject it in to your controller and use it like so;

[HttpGet("hello")]
public ActionResult Hello()
{
    _requestMessageLogger.LogRequest();
    return Ok();
}
  • Related