Right way to work with RSS in ASP.NET Core 1.0 RC2

后端 未结 2 1352
闹比i
闹比i 2020-12-29 09:52

What is the right/best way to get data from an RSS feed using ASP.Net Core 1.0 (RC2) in C#.

I want to work with the data in the RSS feed from my Wordpress blog which

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 10:20

    For the sake of completeness, I'll include the final code which is a stripped down version of the sample @Sock linked to in the 'Build your own XML Parser' section of the answer. @Sock's answer is still the most complete answer, but this sample should be useful for anyone looking for a quick, simple code sample for ASP.NET Core.

    Model

    public class FeedItem
    {
        public string Link { get; set; } 
        public string Title { get; set; } 
        public string Content { get; set; } 
        public DateTime PublishDate { get; set; } 
    }
    

    Controller

    public class ArticlesController : Controller
    {
        public async Task Index()
        {
            var articles = new List();
            var feedUrl = "https://blogs.msdn.microsoft.com/martinkearn/feed/";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(feedUrl);
                var responseMessage = await client.GetAsync(feedUrl);
                var responseString = await responseMessage.Content.ReadAsStringAsync();
    
                //extract feed items
                XDocument doc = XDocument.Parse(responseString);
                var feedItems = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")
                                select new FeedItem
                                {
                                    Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
                                    Link = item.Elements().First(i => i.Name.LocalName == "link").Value,
                                    PublishDate = ParseDate(item.Elements().First(i => i.Name.LocalName == "pubDate").Value),
                                    Title = item.Elements().First(i => i.Name.LocalName == "title").Value
                                };
                articles = feedItems.ToList();
            }
    
            return View(articles);
        }
    
        private DateTime ParseDate(string date)
        {
            DateTime result;
            if (DateTime.TryParse(date, out result))
                return result;
            else
                return DateTime.MinValue;
        }
    }
    

提交回复
热议问题