Create RSS feed in asp.net core 1.0

…衆ロ難τιáo~ 提交于 2019-12-01 09:09:22

They've released a preview NuGet package for Microsoft.SyndicationFeed. On the dotnet/wcf repo, they've provided an example to get you up and running.

EDIT: I've posted a Repo and a NuGet package that serves as a Middleware around this.

Asest
// action to return the feed
[Route("site/GetRssFeed/{type}")]
public IActionResult GetRssFeed(ArticleStatusTypes type)
{
    var feed = _rss.BuildXmlFeed(type);
    return Content(feed, "text/xml");
}


public string BuildXmlFeed(ArticleStatusTypes type)
{
    var key = $"RssFeed{Convert.ToInt32(type)}{_appInfo.ApplicationId}";
    var articles =
            _cache.GetCachedData(key) ??
            _cache.SetCache(key, _service.GetItems(Convert.ToInt32(type), _appInfo.CacheCount));

    StringWriter parent = new StringWriter();
    using (XmlTextWriter writer = new XmlTextWriter(parent))
    {
        writer.WriteProcessingInstruction("xml-stylesheet", "title=\"XSL_formatting\" type=\"text/xsl\" href=\"/skins/default/controls/rss.xsl\"");

        writer.WriteStartElement("rss");
        writer.WriteAttributeString("version", "2.0");
        writer.WriteAttributeString("xmlns:atom", "http://www.w3.org/2005/Atom");

        // write out 
        writer.WriteStartElement("channel");

        // write out -level elements
        writer.WriteElementString("title", $"{_appInfo.ApplicationName} {type}" );
        writer.WriteElementString("link", _appInfo.WebsiteUrl);
        //writer.WriteElementString("description", Description);
        writer.WriteElementString("ttl", "60");

        writer.WriteStartElement("atom:link");
        //writer.WriteAttributeString("href", Link + Request.RawUrl.ToString());
        writer.WriteAttributeString("rel", "self");
        writer.WriteAttributeString("type", "application/rss+xml");
        writer.WriteEndElement();

        if (articles != null)
        {
            foreach (var article in articles)
            {
                writer.WriteStartElement("item");

                writer.WriteElementString("title", article.Title);
                writer.WriteElementString("link", _appInfo.WebsiteUrl); // todo build article path
                writer.WriteElementString("description", article.Summary);

                writer.WriteEndElement();
            }
        }

        // write out 
        writer.WriteEndElement();

        // write out 
        writer.WriteEndElement();
    }

    return parent.ToString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!