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.
- Open Visual Studio.
- Create a new Blazor Server App project.
- Name your project (for example, BlazorRSSFeed) and choose .NET 6.0 (Long-term support) as the framework.
- Click Create.
- 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.
- In Solution Explorer, right-click on the project and select Manage NuGet Packages.
- In the Browse tab, search for System.ServiceModel.Syndication and install the package.
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.
- In the Solution Explorer, right-click on the Services folder (create one if it doesn’t exist) and choose Add > Class.
- Name it RssFeedService.cs.
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
}
}
}
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.
- Open the **Program.cs** file in the root directory of your project.
- 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();
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.
- In the Solution Explorer, navigate to the Pages folder.
- 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");
}
}
Step 6. Update the Navigation Menu.
To access the RSS feed page, you need to add a link to it in the navigation menu.
- Open the Shared/NavMenu.razor file.
- Add the following navigation link.
<NavLink class="nav-link" href="/rssfeed">
<span class="oi oi-list-rich" aria-hidden="true"></span> RSS Feed
</NavLink>
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.
Conclusion
In this article, we demonstrated how to:
- Create a simple Blazor Server application using .NET Core 6.0.
- Build an RssFeedService to fetch data from an external RSS feed.
- Use Dependency Injection (DI) to inject services into Blazor components.
- 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