创建MVC4 RSS源/的WebAPI [英] Create RSS feed in MVC4/WebAPI

查看:172
本文介绍了创建MVC4 RSS源/的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找创建通过MVC4(和/或的WebAPI)RSS订阅源的最佳途径。这篇文章似乎是最适用的的http:// www.strathweb.com/2012/04/rss-atom-mediatypeformatter-for-asp-net-webapi/ 。但它是写在的WebAPI的pre-释天。我用的NuGet把所有的包先进的日期,但试图建立项目扔:

I'm looking for the best way to create an RSS feed via MVC4 (and/or WebAPI). This post seemed the most applicable http://www.strathweb.com/2012/04/rss-atom-mediatypeformatter-for-asp-net-webapi/. But it was written in the pre-Release days of WebAPI. I've used Nuget to bring all packages up-to-date but attempting to build the project tosses:

Error   2   The type or namespace name 'FormatterContext' could not be found (are you missing a using directive or an assembly reference?)  G:\Code\MvcApplication-atomFormatter\MvcApplication-atomFormatter\SyndicationFeedFormatter.cs   38  129 MvcApplication_syndicationFeedFormatter

我发现了一些文章解释说,MediaTypeFormatter自公测显著改变,但我已经找到了需要讨论的code段调整的细节。

I've found a number of articles explaining that the MediaTypeFormatter has changed significantly since beta but I have found details on the adjustments required to the code snippet in question.

有一个展示的RSSFormatter建设的更新的资源?

Is there an updated resource showing the construction of an RSSFormatter?

THX

推荐答案

是我写的教程针​​对测试版。

Yes I wrote that tutorial against Beta.

下面是code升级到RTM版本。

Below is the code updated to RTM version.

一个建议,如果可以的话,就是这个例子中使用的具体类型的简单的白名单,此种RSS / Atom提要是建立(在这种情况下,我的网​​址模型)。理想的情况是在比较复杂的情况,你不得不格式化设置了防止接口,而不是一个具体类型,并有它们应该被公开为RSS所有型号实现该接口。

One advice, if I may, is that this example uses a simple "whitelist" of concrete types for which RSS/Atom feed is build (in this case my Url model). Ideally in more complex scenarios, you'd have the formatter set up against an interface, rather than a concrete type, and have all Models which are supposed to be exposed as RSS to implement that interface.

希望这有助于。

   public class SyndicationFeedFormatter : MediaTypeFormatter
    {
        private readonly string atom = "application/atom+xml";
        private readonly string rss = "application/rss+xml";

        public SyndicationFeedFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue(atom));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue(rss));
        }

        Func<Type, bool> SupportedType = (type) =>
        {
            if (type == typeof(Url) || type == typeof(IEnumerable<Url>))
                return true;
            else
                return false;
        };

        public override bool CanReadType(Type type)
        {
            return SupportedType(type);
        }

        public override bool CanWriteType(Type type)
        {
            return SupportedType(type);
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
        {
            return Task.Factory.StartNew(() =>
            {
                if (type == typeof(Url) || type == typeof(IEnumerable<Url>))
                    BuildSyndicationFeed(value, writeStream, content.Headers.ContentType.MediaType);
            });
        }

        private void BuildSyndicationFeed(object models, Stream stream, string contenttype)
        {
            List<SyndicationItem> items = new List<SyndicationItem>();
            var feed = new SyndicationFeed()
            {
                Title = new TextSyndicationContent("My Feed")
            };

            if (models is IEnumerable<Url>)
            {
                var enumerator = ((IEnumerable<Url>)models).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    items.Add(BuildSyndicationItem(enumerator.Current));
                }
            }
            else
            {
                items.Add(BuildSyndicationItem((Url)models));
            }

            feed.Items = items;

            using (XmlWriter writer = XmlWriter.Create(stream))
            {
                if (string.Equals(contenttype, atom))
                {
                    Atom10FeedFormatter atomformatter = new Atom10FeedFormatter(feed);
                    atomformatter.WriteTo(writer);
                }
                else
                {
                    Rss20FeedFormatter rssformatter = new Rss20FeedFormatter(feed);
                    rssformatter.WriteTo(writer);
                }
            }
        }

        private SyndicationItem BuildSyndicationItem(Url u)
        {
            var item = new SyndicationItem()
            {
                Title = new TextSyndicationContent(u.Title),
                BaseUri = new Uri(u.Address),
                LastUpdatedTime = u.CreatedAt,
                Content = new TextSyndicationContent(u.Description)
            };
            item.Authors.Add(new SyndicationPerson() { Name = u.CreatedBy });
            return item;
        }
    }

这篇关于创建MVC4 RSS源/的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆