Search code examples
c#rest.net-coreasp.net-core-webapimessage-handlers

HttpMessagehandler in a weatherforecast


I am trying to implement the HttpMessageHandler in the weather forecast example for ASP.NET Core Web API.

Basically I want a HttpMessageHandler class to intercept the HttpRequest before it hits the controller and again before sending the response to a client.

Just as the message inspector in WCF (BeforeSend and AfterReceive), but I cannot find a working example with the WeatherForecast .NET Core template.

How can I configure that my MessageHandler class?

public class MessageHandler1 : DelegatingHandler  
{  
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
    {  
        var response = new HttpResponseMessage(HttpStatusCode.OK)  
            {  
                Content = new StringContent("We got your request but did not process it !!")  
            };  

        var tsc = new TaskCompletionSource<HttpResponseMessage>();  
        tsc.SetResult(response);  

        return await tsc.Task;  
    }
}

I can create this MessageHandler1 class somewhere in my code, but how can I get it initialized? Do I use my startup Program.cs? And what code gets it activated in my rest API application?


Solution

  • Yes, you need to use Program.cs to inject your interceptor. Inside Program.cs add you interceptor:

    ...
    var app = builder.Build();
    
    //HTTP response interceptor
    app.UseMiddleware<MyMiddleware>();
    ...
    

    then in your MyMiddleware interceptor do this next:

    public class MyMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<MyMiddleware> _logger;
        private readonly IHostEnvironment _environment;
    
        public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger, IHostEnvironment environment)
        {
            _next = next;
            _logger = logger;
            _environment = environment;
        }
    
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                // do your stuff
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                
                // do your stuff
    
                await context.Response.WriteAsync();
            }
        }
    }
    

    Additional information you can find here: Middleware Example