6

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

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

4

1 回答 1

1

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

对于您的上述情况,您需要派生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() }));
于 2013-07-15T15:32:36.157 回答