将HttpRequestMessage转换为OwinRequest和OwinResponse转换为HttpResponseMessage

时间:2013-07-15 13:59:46

标签: c# asp.net-web-api owin katana

我有一个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);
    }
}

Handler非常简单,什么都不做。

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。只是因为我无法想办法做我想做的事。

1 个答案:

答案 0 :(得分:1)

是的,这个经验需要改进,因为例外被忽略了。

对于上面的场景,您需要从HttpMessageHandler而不是DelegatingHandler派生,因为委托处理程序会尝试将请求委托给处理程序。(示例:异常提及{{1} }})

例如,以下内容可行:

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