【问题标题】:Reading custom Content-Type (f.e. StackOverflow) feeds using HttpClient from WebAPI使用来自 WebAPI 的 HttpClient 读取自定义 Content-Type (f.e. StackOverflow) 提要
【发布时间】:2012-03-15 22:45:18
【问题描述】:

我非常喜欢 HttpClient 的架构方式 - 但我不知道如何添加“不太标准”的媒体类型以由 XmlSerializer 处理。

这段代码:

var cli = new HttpClient();
cli
    .GetAsync("http://stackoverflow.com/feeds/tag?tagnames=delphi&sort=newest")
    .ContinueWith(task =>
    {
        task.Result.Content.ReadAsAsync<Feed>();
    }); 

当指向 Content-Type 为“text/xml”的原子提要时工作正常,但示例中的那个失败并显示 “No 'MediaTypeFormatter' is available to read an object of type 'Feed'带有媒体类型'application/atom+xml'" 消息。 我尝试了为 XmlMediaTypeFormatter 指定 MediaRangeMappings 的不同组合(作为参数传递给 ReadAsAsync),但没有成功。

配置 HttpClient 以将“application/atom+xml”和“application/rss+xml”映射到 XmlSerializer 的“推荐”方式是什么?

【问题讨论】:

    标签: c# .net wcf wcf-web-api


    【解决方案1】:

    问题是您正试图将结果直接转换为 Feed。正如错误清楚地表明的那样,它无法弄清楚我们如何将application/atom+xml 转换为Feed

    您可能必须以 XML 形式返回,然后使用 XmlReader 来初始化您的 Feed。

    另一种方法是提供您自己的媒体格式化程序 - 以及封装它的实现。

    【讨论】:

    • 请注意 - 如果 atom 提要具有“text/xml”或“application/xml”作为 Content-Type,“将结果直接转换为提要”工作正常,在后台使用 XmlSerializer .所以这个问题必须有一个只使用配置/映射的解决方案。
    • @SergeyAldoukhov 所以如果内容类型是 XML,它可以工作吗?我很惊讶……他们一定是把这个翻译从那个命名空间+根硬编码到了 Feed 中,如果它真的很糟糕。
    【解决方案2】:

    这是有效的代码(感谢ASP.net forum thread):

    public class AtomFormatter : XmlMediaTypeFormatter
    {
        public AtomFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/atom+xml"));
        }
    
        protected override bool CanReadType(Type type)
        {
            return base.CanReadType(type) || type == typeof(Feed);
        }
    }
    
    var cli = new HttpClient();
    cli
        .GetAsync("http://stackoverflow.com/feeds/tag?tagnames=delphi&sort=newest")
        .ContinueWith(task =>
        {
            task.Result.Content.ReadAsAsync<Feed>(new[] { new AtomFormatter });
        }); 
    

    仍然希望看到不使用 XmlMediaTypeFormatter 子类的解决方案 - 有人吗?

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 2022-08-10
      • 1970-01-01
      • 2016-09-07
      相关资源
      最近更新 更多