gpt4 book ai didi

c# - 将 HttpRequestMessage 转换为 OwinRequest 并将 OwinResponse 转换为 HttpResponseMessage

转载 作者:太空狗 更新时间:2023-10-29 21:58:16 25 4
gpt4 key购买 nike

我有一个 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'发生在System.Net.Http.dll

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

最佳答案

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

对于上述情况,您需要从 HttpMessageHandler 而不是 DelegatingHandler 派生,因为委托(delegate)处理程序会尝试将请求委托(delegate)给它之后的处理程序。(示例:异常提到 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() }));

关于c# - 将 HttpRequestMessage 转换为 OwinRequest 并将 OwinResponse 转换为 HttpResponseMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17656066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com