slaveOftime
noteswebRSSdotnet

How to create RSS feed in dotnet

2023-02-09

Nowadays, I feel RSS is not that popular, at least for me, I rarely use it. When I try to update my blog site, I decided to support that.

Different language has different solution, and there are also some proxy like service hosted in docker to convert any website to a RSS feed. Basically it just generate a xml file with some specifications.

I decided to use System.ServiceModel.Syndication package from Microsoft. The basic usage is:

1. Prepare the post items

let item = SyndicationItem(
    Id = post.Id.ToString(),
    BaseUri = Uri host,
    Title = TextSyndicationContent post.Title,
    PublishDate = post.CreatedTime,
    LastUpdatedTime = post.UpdatedTime
)

Something to be careful is for the main link we should use CreateAlternateLink, so some RSS reader can use it to redirect the consumer to browser.

item.Links.Add(SyndicationLink.CreateAlternateLink(Uri $"{host}/blog/{post.Slug}"))

Another thing to be careful is for the description or summary field. I tested with couple of RSS readers, can will display the description as the content. So instead of set the content to the content field. I use summary field, and it also supports html.

item.Summary <- SyndicationContent.CreateHtmlContent(content)

For my site, I have to fetch the post after the site is started to get that html for the post. But I think brief description is enough, and can simplify the generation a lot, and also reduce the final feed content.

2. Create a feed

This is pretty simple:

SyndicationFeed(
    Title = TextSyndicationContent(siteTitle),
    Description = TextSyndicationContent(siteDescription),
    Items = items
)

But may still need to be careful to add below links, one is CreateAlternateLink, one is CreateSelfLink.

feed.Links.Add(SyndicationLink.CreateAlternateLink(Uri host))
feed.Links.Add(SyndicationLink.CreateSelfLink(Uri $"{host}/feed", "application/rss+xml"))

3. Finally we can create a file and cache it

Below I support two formatters, one is Rss20FeedFormatter, another one is Atom10FeedFormatter.

use memoryStream = new MemoryStream()
use xmlWriter = XmlWriter.Create(memoryStream, XmlWriterSettings(Encoding = Encoding.UTF8))
match feedType with
| RSS -> Rss20FeedFormatter(feed).WriteTo(xmlWriter)
| ATOM -> Atom10FeedFormatter(feed).WriteTo(xmlWriter)
xmlWriter.Flush()

let bytes = memoryStream.ToArray()
let fileName = feedCacheFile feedType
File.WriteAllBytes(fileName, bytes)

Do you like this post?