Building a Blazor Server App to Fetch RSS Feeds Using .NET Core

Introduction

In this article, we will guide you through building a simple Blazor Server Application using .NET Core 6.0 that fetches an RSS feed from the C# Corner website and displays the latest content. This project will showcase how to use dependency injection and HttpClient to retrieve RSS feeds and render them on a web page.

Prerequisites

To follow this article, you need.

  • Visual Studio 2022 (or later)
  • .NET Core 6.0 SDK
  • Basic understanding of Blazor and .NET Core

Step 1. Create a Blazor Server Application.

  1. Open Visual Studio.
    Open Visual Studio
  2. Create a new Blazor Server App project.
    Blazor Server App
  3. Name your project (for example, BlazorRSSFeed) and choose .NET 6.0 (Long-term support) as the framework.
    BlazorRSSFeed
  4. Click Create.
    Create
  5. Once the project is created, you will have a basic Blazor Server application structure in place.

Step 2. Set Up the Required NuGet Packages.

We need the System.ServiceModel.Syndication package to handle RSS feed processing.

  1. In Solution Explorer, right-click on the project and select Manage NuGet Packages.
  2. In the Browse tab, search for System.ServiceModel.Syndication and install the package.
    Solution Explorer

Step 3. Create the RssFeedService.

You need to create a service that will fetch the RSS feed data from the C# Corner website. The service will use HttpClient to request the data.

  1. In the Solution Explorer, right-click on the Services folder (create one if it doesn’t exist) and choose Add > Class.
  2. Name it RssFeedService.cs.
    Services folder
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.ServiceModel.Syndication;
    using System.Threading.Tasks;
    using System.Xml;
    
    public class RssFeedService
    {
        private readonly HttpClient _httpClient;
    
        public RssFeedService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
    
        public async Task<string> GetRssFeedAsync()
        {
            var response = await _httpClient.GetStringAsync("https://www.c-sharpcorner.com/rss/latestcontentall.aspx");
            return response;
        }
    
        public async Task<List<SyndicationItem>> GetRssFeedAsync(string feedUrl)
        {
            try
            {
                using var response = await _httpClient.GetAsync(feedUrl);
                response.EnsureSuccessStatusCode(); // This will throw if the status code is not 200-299
                using var stream = await response.Content.ReadAsStreamAsync();
                using var xmlReader = XmlReader.Create(stream);
                var syndicationFeed = SyndicationFeed.Load(xmlReader);
                return syndicationFeed?.Items.ToList() ?? new List<SyndicationItem>();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                return new List<SyndicationItem>(); // Return empty if an error occurs
            }
        }
    }
    Class

Step 4. Register RssFeedService in Dependency Injection.

You must register RssFeedService in the Dependency Injection (DI) container so it can be injected into your Blazor components.

  1. Open the **Program.cs** file in the root directory of your project.
  2. Add the following line to register RssFeedService with HttpClient.
    using BlazorRSSfeed.Data;
    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddRazorPages();                      // For Razor Pages
    builder.Services.AddServerSideBlazor();                // For Blazor Server
    builder.Services.AddHttpClient<RssFeedService>();      // Register RssFeedService with HttpClient
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    
    app.MapBlazorHub();
    app.MapFallbackToPage("/_Host");
    
    app.Run();
    Dependency Injection

Step 5. Create a Blazor Component to Display the RSS Feed.

Now that the service is ready and registered, you can create a Blazor component to fetch and display the RSS feed.

  1. In the Solution Explorer, navigate to the Pages folder.
  2. Right-click and select Add > Razor Component. Name it RssFeed.razor.

Here’s the code for RssFeed.razor.

@page "/rssfeed"
@inject RssFeedService RssFeedService

<h3>Latest C# Corner Feeds</h3>

<ul>
    @if (rssItems == null)
    {
        <li>Loading...</li>
    }
    else
    {
        @foreach (var item in rssItems)
        {
            <li>
                <a href="@item.Links.FirstOrDefault()?.Uri" target="_blank">@item.Title.Text</a>
                <p>@item.Summary.Text</p>
            </li>
        }
    }
</ul>

@code {
    private List<System.ServiceModel.Syndication.SyndicationItem> rssItems;

    protected override async Task OnInitializedAsync()
    {
        rssItems = await RssFeedService.GetRssFeedAsync("https://www.c-sharpcorner.com/rss/latestcontentall.aspx");
    }
}

Razor Component

Step 6. Update the Navigation Menu.

To access the RSS feed page, you need to add a link to it in the navigation menu.

  1. Open the Shared/NavMenu.razor file.
  2. Add the following navigation link.
    <NavLink class="nav-link" href="/rssfeed">
        <span class="oi oi-list-rich" aria-hidden="true"></span> RSS Feed
    </NavLink>
    
    RSS feed page

Step 7. Run the Application.

Now that everything is set up, run the application by pressing F5 or clicking on the Run button in Visual Studio.

Once the application starts, navigate to the RSS Feed link in the sidebar. You should see the latest content from the C# Corner RSS feed displayed on the page.

RSS Feed link

Conclusion

In this article, we demonstrated how to:

  1. Create a simple Blazor Server application using .NET Core 6.0.
  2. Build an RssFeedService to fetch data from an external RSS feed.
  3. Use Dependency Injection (DI) to inject services into Blazor components.
  4. Render RSS feeds data dynamically within a Blazor component.

This is a basic yet powerful application that highlights how Blazor can be used for real-time data fetching and rendering. You can further improve it by formatting the feed, adding error handling, or integrating additional features.

Reference: Create A Simple Blazor Server Application With .NET Core 3.0


Similar Articles