将HttpRequestMessage转换为OwinRequest,将OwinResponse转换为HttpRespon

本文关键字:转换 HttpRespon OwinResponse OwinRequest HttpRequestMessage | 更新日期: 2023-09-27 18:22:26

我有一个web API消息处理程序MyHandler,我想在OWIN管道中作为中间件运行。所以像这样配置处理程序。

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);
    }
}

处理程序非常简单,什么也不做。

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;
    }
}

我在SendAsync里面放了一个断点,它确实断了,但接下来的base.SendAsync无声地爆炸了,我看到了A first chance exception of type 'System.InvalidOperationException' occurred in System.Net.Http.dll

我可以很容易地将MyHandler添加到config.MessageHandlers,它将在Web API管道中完美运行,但这不是我想做的。我想在OWIN管道中运行MyHandler。这可能吗?应该是。否则,我想使用扩展方法UseHttpMessageHandler是没有意义的。只是我想不出一种方法来做我想做的事。

将HttpRequestMessage转换为OwinRequest,将OwinResponse转换为HttpRespon

是的,这种体验需要改进,因为异常被默默地忽略了。

对于上面的场景,您需要从HttpMessageHandler而不是DelegatingHandler派生,因为委派处理程序会尝试将请求委派给之后的处理程序。(例如:异常提到Message=The inner handler has not been assigned

例如,以下方法可行:

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);
    }
}

为了创建一个处理程序链,您可以执行以下操作:

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