Back to "Ajouter un feed RSS avec ASP.NET Core"

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

ASP.NET RSS

Ajouter un feed RSS avec ASP.NET Core

Wednesday, 07 August 2024

Introduction

RSS (et Atom) est encore le seul format largement adopté pour la syndication de contenus . C’est un format XML simple qui peut être consommé par une vaste gamme de lecteurs d’aides à l’alimentation M SK4 Dans ce postMSC5 IM SK6je vous montrerai comment ajouter un feed RSS à votre ASPMNK7NET Core applicationMRK8

Création du feed

En fait, le noyau de ce projet consiste à créer un document XML pour les flux RSS. Le code ci-dessous prend une liste des RssFeedItem et génère l’XML pour le feed. RssFeedItem class est une classe simple qui représente un objet dans le feed.

    public string GenerateFeed(IEnumerable<RssFeedItem> items, string categoryName = "")
    {
        XNamespace atom = "http://www.w3.org/2005/Atom";
        var feed = new XDocument(
            new XDeclaration("1.0", "utf-8", null),
            new XElement("rss",    new XAttribute(XNamespace.Xmlns + "atom", atom.NamespaceName), new XAttribute("version", "2.0"),
                new XElement("channel",
                    new XElement("title", !string.IsNullOrEmpty(categoryName) ? $"mostlylucid.net for {categoryName}" : $"mostlylucid.net"),
                    new XElement("link", $"{GetSiteUrl()}/rss"),
                    new XElement("description", "The latest posts from mostlylucid.net"),
                    new XElement("pubDate", DateTime.UtcNow.ToString("R")),
                    new XElement(atom + "link", 
                        new XAttribute("href", $"{GetSiteUrl()}/rss"), 
                        new XAttribute("rel", "self"), 
                        new XAttribute("type", "application/rss+xml")),
                    from item in items
                    select new XElement("item",
                        new XElement("title", item.Title),
                        new XElement("link", item.Link),
                        new XElement("guid", item.Guid, new XAttribute("isPermaLink", "false")),
                        new XElement("description", item.Description),
                        new XElement("pubDate", item.PubDate.ToString("R")),
                        from category in item.Categories
                        select new XElement("category", category)
                    )
                )
            )
        );

        var settings = new XmlWriterSettings
        {
            Indent = true,
            Encoding = new UTF8Encoding(false) // UTF-8 without BOM
        };

        using (var memoryStream = new MemoryStream())
        using (var writer = XmlWriter.Create(memoryStream, settings))
        {
            feed.Save(writer);
            writer.Flush();
            return Encoding.UTF8.GetString(memoryStream.ToArray());
        }
    }

Points à noter dans le code ci-dessus: Nous devons créer le nom de domaine Atom et l'injecter dans le document XML pour appuyer atom:link TÉU, TM, TMÉU, TACI, TC:

     XNamespace atom = "http://www.w3.org/2005/Atom";
        var feed = new XDocument(
            new XDeclaration("1.0", "utf-8", null),
            new XElement("rss",    new XAttribute(XNamespace.Xmlns + "atom", atom.NamespaceName), new XAttribute("version", "2.0"),

Encodage UTF-8

Bien que nous spécifions utf-8 ici bien ASP.NET Core ignore que ...because c'est ce qu'il est specialM SK2. Au lieu de cela, nous devons veiller à ce que les chaînes générées dans le document soient en fait UTFMSC4 J'avais pensé ceci

   var settings = new XmlWriterSettings
        {
            Indent = true,
            Encoding = new UTF8Encoding(false) // UTF-8 without BOM
        };

Mais nous devons le faire.

        using (var memoryStream = new MemoryStream())
        using (var writer = XmlWriter.Create(memoryStream, settings))
        {
            feed.Save(writer);
            writer.Flush();
            return Encoding.UTF8.GetString(memoryStream.ToArray());
        }

De cette façon, il produit en réalité un document XML avec utf-8 codage.

Le contrôleur

De là il' est assez simple dans le RSSController, nous avons une méthode qui accepte category et startdate (à l'heure actuelle, une fonction super secrete ??) et retourne le feed

    [HttpGet]
    public IActionResult Index([FromQuery] string category = null, [FromQuery] string startDate = null)
    {
        DateTime? startDateTime = null;
        if (DateTime.TryParseExact(startDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None,
                out DateTime startDateTIme))
        {
            logger.LogInformation("Start date is {startDate}", startDate);
        }

        var rssFeed = rssFeedService.GenerateFeed(startDateTime, category);
        return Content(rssFeed, "application/rss+xml", Encoding.UTF8);
    }

Ensuite, dans le `_Layout.cshtmlM SK1 nous ajoutons un lien au feed:

        <link rel="alternate" type="application/rss+xml"
              title="RSS Feed for mostlylucid.net"
              href="/rss" />

Cela garantit que le feed peut être 'autodétecté' par les lecteurs de feedsM SK2

logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.