在 C# 中使用 ASP.Net Core 1.0 (RC2) 从 RSS 提要获取数据的正确/最佳方法是什么。
我想使用来自我的 Wordpress 博客 https://blogs.msdn.microsoft.com/martinkearn/feed/ 的 RSS 提要中的数据。
我知道在 ASP.net 4.x 中,你会使用 RssReader
或 SyndicationFeed
但我找不到 ASP.net 核心的等效项。
就我所知,它返回原始提要,但我不知道如何从中提取数据。我想枚举项目并获得 title
和 description
从每一个
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();
}
最佳答案
为了完整起见,我将在答案的“构建您自己的 XML 解析器”部分中包含最终代码,它是链接到示例 @Sock 的精简版本。 @Sock 的答案仍然是最完整的答案,但此示例对于寻找快速、简单的 ASP.NET Core 代码示例的任何人都应该有用。
模型
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<IActionResult> Index()
{
var articles = new List<FeedItem>();
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;
}
}
关于rss - 在 ASP.NET Core 1.0 RC2 中使用 RSS 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309440/