0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
codingjoe
  • 707
  • 5
  • 15
  • 32
  • Take a look at [DelegatingHandler](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.delegatinghandler?view=net-7.0) – Ryan Aug 31 '23 at 04:45

2 Answers2

1

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

DenisMicheal.k
  • 197
  • 2
  • 12
Jivopis
  • 121
  • 11
1

Just Like Scotty13 had pointed out in ASP.NET Core to intercept a request before it hits your controller you will need to use a middleware. Take a look at the ASP.NET CORE request cycle.

The HttpMessageHandler is a class at a lower level than middleware it can intercept outgoing HTTP requests and incoming responses . They work with HttpClient and is primarily used in scenarios where you need to customize the behavior of outgoing HTTP requests or incoming HTTP responses.

DenisMicheal.k
  • 197
  • 2
  • 12