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?
Yes, you need to use
Program.csto inject your interceptor. InsideProgram.csadd you interceptor:then in your
MyMiddlewareinterceptor do this next:Additional information you can find here: Middleware Example