使用 HttpClient 从 WebAPI 读取自定义内容类型 (fe StackOverflow) feed
我非常喜欢 HttpClient 的架构 - 但我不知道如何添加由 XmlSerializer 处理的“不太标准”的媒体类型。
此代码:
var cli = new HttpClient();
cli
.GetAsync("http://stackoverflow.com/feeds/tag?tagnames=delphi&sort=newest")
.ContinueWith(task =>
{
task.Result.Content.ReadAsAsync<Feed>();
});
当指向内容类型为“text/xml”的原子提要时工作正常,但示例中的代码失败,并显示“没有‘MediaTypeFormatter’可用于读取类型为‘Feed’的对象”带有媒体类型“application/atom+xml””消息。 我尝试了为 XmlMediaTypeFormatter 指定 MediaRangeMappings 的不同组合(作为参数传递给 ReadAsAsync),但没有成功。
配置 HttpClient 将“application/atom+xml”和“application/rss+xml”映射到 XmlSerializer 的“推荐”方法是什么?
I like a lot how the HttpClient is architectured - but I can't figure out how to add a "not quite standard" media type to be handled by the XmlSerializer.
This code:
var cli = new HttpClient();
cli
.GetAsync("http://stackoverflow.com/feeds/tag?tagnames=delphi&sort=newest")
.ContinueWith(task =>
{
task.Result.Content.ReadAsAsync<Feed>();
});
works fine when pointed to atom feeds that have Content-Type of "text/xml", but the one in the example fails with the "No 'MediaTypeFormatter' is available to read an object of type 'Feed' with the media type 'application/atom+xml'" message.
I tried different combinations of specifying MediaRangeMappings for the XmlMediaTypeFormatter (to be passed as an argument to ReadAsAsync) but with no success.
What is the "recommended" way to configure the HttpClient to map "application/atom+xml" and "application/rss+xml" to XmlSerializer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是有效的代码(归功于 ASP.net 论坛thread):
仍然希望看到一个无需子类化 XmlMediaTypeFormatter 的解决方案 - 有人吗?
Here is the code that works (credits to ASP.net forum thread):
Still, would like to see a solution without subclassing XmlMediaTypeFormatter - anybody?
问题是您试图将结果直接转换为 Feed。正如错误明确指出的那样,它无法弄清楚我们如何将
application/atom+xml
转换为Feed
。您可能必须以 XML 形式返回,然后使用 XmlReader 来初始化您的 Feed。
另一种方法是提供您自己的媒体格式化程序 - 以及封装它的实现。
The problem is that you are trying to convert the result straight to Feed. As error is clearly saying, it cannot figure our how to convert the
application/atom+xml
intoFeed
.You would have to perhaps return as XML and then use and XmlReader to initialise your Feed.
Alternative is to provide your own media formatter - and implementation which encapsulates this.