如何在View中通过SyndicationFeed显示RSS

时间:2015-09-12 18:35:10

标签: c# asp.net xml asp.net-mvc rss

我是ASP.NET的新手,我非常感兴趣的是从网站(example)拉取和显示RSS提要。我找到了几个很棒的教程,但没有一个教程演示如何在视图中设置样式?

我注意到在运行我的ASP.NET MVC项目时,我可以在Internet Explorer中看到该源,但它只是Chrome中未格式化的XML。如何实现一个简单的样式来适当地呈现它?

仅供参考我提取雅虎财经头条,所以这里有一些background供参考。

HomeController.cs

public RssActionResult Index()
    {
        SyndicationFeed mainFeed = new SyndicationFeed();

        foreach (var feed in GetRssFeeds())
        {
            Uri feedUri = new Uri(feed);
            SyndicationFeed syndicationFeed;
            using (XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri))
            {
                syndicationFeed = SyndicationFeed.Load(reader);
            }

            syndicationFeed.Id = feed;
            SyndicationFeed tempFeed = new SyndicationFeed(
                mainFeed.Items.Union(syndicationFeed.Items).OrderByDescending(u => u.PublishDate));

            mainFeed = tempFeed;
        }

        return new RssActionResult() { Feed = mainFeed }; 
    }

public class RssActionResult : ActionResult
    {
        public SyndicationFeed Feed { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {

            context.HttpContext.Response.ContentType = "application/rss+xml";
            Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed);

            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                rssFormatter.WriteTo(writer);
            }
        }
    }

    private static List<string> GetRssFeeds()
    {
        List<string> feeds = new List<string>();

        feeds.Add("http://finance.yahoo.com/rss/headline?s=msft,goog,aapl");
        //feeds.Add("http://www.nickharris.net/feed/");  //from example site
        //feeds.Add("http://feeds.feedburner.com/ntotten");  //from example site

        return feeds;
    }

0 个答案:

没有答案