Convert HttpRequestMessage to OwinRequest and OwinResponse to HttpResponseMessage

I have a MyHandler web API message handler that I want to run in the OWIN pipeline as middleware. So setting up a handler like this.

 public class Startup { public void Configuration(IAppBuilder app) { app.UseHttpMessageHandler(new MyHandler()); HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( "DefaultWebApi", "{controller}/{id}", new { id = RouteParameter.Optional }); app.UseWebApi(config); } } 

The handler is very simple and does nothing.

 public class MyHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { // <--- breakpoint here var response = await base.SendAsync(request, cancellationToken); return response; } } 

I set a breakpoint inside SendAsync and it breaks, but the next base.SendAsync bombs are silent and I see A first chance exception of type 'System.InvalidOperationException' occurred in System.Net.Http.dll .

I can easily add MyHandler to config.MessageHandlers and it will work perfectly in the web API pipeline, but that is not what I want to do. I want to run MyHandler in the OWIN pipeline. Is it even possible? It should be. Otherwise, it makes no sense to use the UseHttpMessageHandler extension UseHttpMessageHandler . I just could not understand how to do what I want to do.

+6
source share
1 answer

Yes, this experience needs to be improved since the exception is ignored.

For your above scenario, you will need to infer from the HttpMessageHandler instead of the DelegatingHandler , as the delegation handler will try to delegate the request to the handlers after it (example: exception mentioned Message=The inner handler has not been assigned )

For example, the following will work:

 appBuilder.UseHttpMessageHandler(new MyNonDelegatingHandler()); public class MyNonDelegatingHandler : HttpMessageHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StringContent("Hello!"); return Task.FromResult<HttpResponseMessage>(response); } } 

And to create a chain of handlers, you can do the following:

 appBuilder.UseHttpMessageHandler(HttpClientFactory.CreatePipeline(innerHandler: new MyNonDelegatingMessageHandler(), handlers: new DelegatingHandler[] { new DelegatingHandlerA(), new DelegatingHandlerB() })); 
+1
source

Source: https://habr.com/ru/post/949471/


All Articles