Converting HttpRequestMessage to OwinRequest and O

2019-06-18 16:05发布

问题:

I have a web API message handler MyHandler that I want to run in OWIN pipeline as a middleware. So configuring the 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);
    }
}

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 put a break point inside SendAsync and it does break but the following base.SendAsync bombs silently and I see A first chance exception of type 'System.InvalidOperationException' occurred in System.Net.Http.dll.

I can quite easily add MyHandler to config.MessageHandlers and it will run perfect in the Web API pipeline but that's not what I want to do. I want to run MyHandler in the OWIN pipeline. Is this possible at all? It should be. Otherwise, there is no point in having the extension method UseHttpMessageHandler, I guess. Just that I couldn't figure out a way to do what I want to do.

回答1:

Yeah, this experience needs to be improved as the exception is silently ignored.

For your above scenario, you would need to derive from HttpMessageHandler instead of DelegatingHandler as the delegating handler would try to delegate the request to handlers after it.(example: The exception mentions Message=The inner handler has not been assigned)

For example, the following would 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 for creating a chain of handlers, you could do the following:

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