【问题标题】:Wrapping WebApi responses using DelegatingHandler使用 DelegatingHandler 包装 WebApi 响应
【发布时间】:2016-08-08 08:46:41
【问题描述】:

我正在尝试使用 DelegatingHandler 来包装我的 Web API 响应。我以this 为例。

在某些时候需要从响应对象中读取内容:

if (response.TryGetContentValue(out content) && ...)

解决方案不起作用,因为 response.TryGetContentValue(out content) 实际上没有返回任何内容(或填充 content 变量)。

但是,如果我将代码“更改”为...

response.Content.ReadAsAsync<object>().Result;

...它确实有效。

我希望TryGetContentValueContent.ReadAsAsync 返回相同的值。为什么不是这样?

编辑:

【问题讨论】:

  • 你能确认一下 TryGetContentValue 是返回真还是假吗?
  • 您能否在调用 TryGetContentValue 时检查 Content 属性的值(以及什么类型)?
  • @MichałKomorowski:它返回错误
  • @AlekseyL.: 只是为了格式化问题...
  • @MichałKomorowski:类型为System.Net.HTTP.StringContent。但是,当我使用ReadAsAsync 检索它时,我强制它成为一个对象。这会自动反序列化它吗..?

标签: c# asp.net-web-api delegatinghandler


【解决方案1】:

如果您查看 the source codeHttpResponseMessageExtensions.TryGetContentValue 方法,您会看到类似:

ObjectContent content = response.Content as ObjectContent;
if (content != null)
{
     ...
}

value = default(T);
return false;

这意味着该方法假定HttpResponseMessage.Content 属性将返回ObjectContent 类型的实例。但是,在您的情况下,它是 StringContent,不能转换为 ObjectContent

【讨论】:

  • 我确实看过源代码,不知何故我认为ObjectContent 可以转换为StringContent...谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-13
相关资源
最近更新 更多