Search code examples
c#databaseentity-frameworkmiddleware

Intercepting HttpRequest and log contents to a database


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


Solution

  • Here is what I was looking for. I used a middleware.

    using Issue2.Model;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace Issue2.Middleware
    {
        // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
        public class Middleware1
        {
            private readonly RequestDelegate _next;
    
            public Middleware1(RequestDelegate next)
            {
                _next = next;
            }
    
            public Task Invoke(HttpContext httpContext, AppDbContext appDbContext)
            {
                var status = httpContext.Response.StatusCode;
                var url = httpContext.Request.Host.ToString();
                var method = httpContext.Request.Method.ToString();
                appDbContext.requestMessages.Add(new RequestMessage { Received = DateTime.Now, Method = method, Url = url, Status = status });
                appDbContext.SaveChanges();
                return _next(httpContext);
            }
        }
    
        // Extension method used to add the middleware to the HTTP request pipeline.
        public static class Middleware1Extensions
        {
            public static IApplicationBuilder UseMiddleware1(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<Middleware1>();
            }
        }
    }