Search code examples
c#mediatorminimal-apis

How to access HttpContext from IRequestHandler using Mediator - Minimal API (C#)


Is there a way to access HttpContext from a request handler? I added a filter to my (minimal API) endpoint to validate the API key, coming from the request headers. Upon successful validation I need the value to Generate JWT for subsequent requests.

Is there a workaround to this? Need a code sample.


Solution

  • Using Carter, it would be something like this (but it is just matter of using equivalent for non-Carter implementation):

    public interface ITokenGrabber
    {
        void SetToken(string token);
        string GetToken();
    }
    
    public class TokenGrabber : ITokenGrabber
    {
        private string _token;
    
        public string GetToken() => _token;
    
        public void SetToken(string token) => _token = token;
    }
    
    public class SampleFilter : IEndpointFilter
    {
        public ValueTask<object> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
        {
            var grabber = context.HttpContext.RequestServices.GetService<ITokenGrabber>();
    
            string token = context.HttpContext.Request.Headers["Authorization"];
                
            grabber.SetToken(token);
    
            return next(context);
        }
    }
    
        public class SomeHandler
            : IRequestHandler<SomeRequest>
        {
            private readonly ITokenGrabber _grabber;
    
            public GetAllExercisesQueryHandle(ITokenGrabber grabber)
            {
                _grabber = grabber;
            }
    
            public Task Handle(SomeRequestrequest, CancellationToken cancellationToken)
            {
                Console.WriteLine(_grabber.GetToken());
                
                return ...
            }
        }
    

    Make sure ITokenGrabber is properly configured with scoped lifetime:

    builder.Services.AddScoped<ITokenGrabber, TokenGrabber>();