Create A Simple Blazor Server Application With .NET Core 3.0

Introduction

Blazor is a new framework built by Microsoft for creating interactive client-side web UI with a .NET codebase. Microsoft has recently launched the .NET Core 3.0 framework. They have shipped the Blazor framework along with this version. In Blazor, we can use C# for both server-side and client-side logic.

Using .NET for client-side web development offers the following advantages.

  • Write code in C# instead of JavaScript.
  • Leverage the existing .NET ecosystem of .NET libraries.
  • Share app logic across server and client.
  • Build on a common set of languages, frameworks, and tools that are stable, feature-rich, and easy to use.

Currently, two types of Blazor applications are available.

  • Blazor Web Assembly and
  • Blazor Server

Blazor WebAssembly is a single-page app framework for building interactive client-side web apps. NET. Running .NET code inside web browsers is made possible by WebAssembly (abbreviated wasm). WebAssembly is a compact bytecode format optimized for fast download and maximum execution speed. WebAssembly is an open web standard and is supported in web browsers without plugins.

While the Blazor server decouples component rendering logic from how UI updates are applied. Blazor server provides the support for hosting Razor components on the server in an ASP.NET Core app. UI updates are handled over a SignalR connection.

The runtime handles sending UI events from the browser to the server and applies UI updates sent by the server back to the browser after running the components.

The connection used by the Blazor server to communicate with the browser is also used to handle JavaScript interop calls.

Please note that Blazor WebAssembly is still under preview mode and will be ready by May 2020 as per Microsoft.

Please refer to this official Microsoft link to get more details about the Blazor framework.

We can see, how to create a Blazor server app with .NET Core 3.0 SDK step by step.

To develop .NET Core 3.0 SDK applications, you must have Visual Studio 2019 version 16.3 or higher. The Blazor server template is already shipped with .NET Core 3.0 SDK. No need to install it separately.

Create a Blazor server app using Visual Studio 2019

Open Visual Studio 2019 and choose the “Create a new project” option. It will show the available project templates and we can choose the “Blazor App” template.

Blazor App

We can give a valid name and physical location to the project. After giving the project name, we can choose the default “Blazor Server App” template and click the “Create” button.

Blazor Server App

Our new Blazor project will be ready shortly. You can see the below project folder structure.

Blazor project

There is a “wwwroot” folder containing CSS, bootstrap, and favicon files. You can see a “Data” folder which contains a model class and service class for the default weather forecast component. The “Page” folder contains the “_Host. cshtml” and other four razor component files. We can see a “Shared” folder which contains “MainLayout” and “NavMenu” shared components files. You can also see an “App” component file. Like other .NET Core applications, we have both Programs. cs and Startup. cs files as well.

As I mentioned earlier, we are going to fetch the latest post details from C# Corner, using their RSS feeds. We can create a “Feed” model class under the “Data” folder and define properties.

Feed. cs

using System;

namespace BlazorSample.Data
{
    public class Feed
    {
        public string Link { get; set; }
        public string Title { get; set; }
        public string FeedType { get; set; }
        public string Author { get; set; }
        public string Content { get; set; }
        public DateTime PubDate { get; set; }
        public string PublishDate { get; set; }

        public Feed()
        {
            Link = "";
            Title = "";
            FeedType = "";
            Author = "";
            Content = "";
            PubDate = DateTime.Today;
            PublishDate = DateTime.Today.ToString("dd-MMM-yyyy");
        }
    }
}

We can create the service class for getting RSS feed data from C# Corner and add the business logic inside the service.

RssFeedService.cs

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BlazorSample.Data
{
    public class RssFeedService
    {
        public async Task<List<Feed>> GetFeedsAsyc()
        {
            CultureInfo culture = new CultureInfo("en-US");

            try
            {
                XDocument doc = XDocument.Load("https://www.c-sharpcorner.com/rss/latestcontentall.aspx");
                var entries = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")
                              select new Feed
                              {
                                  Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
                                  Link = (item.Elements().First(i => i.Name.LocalName == "link").Value).StartsWith("/") ? "https://www.c-sharpcorner.com" + item.Elements().First(i => i.Name.LocalName == "link").Value : item.Elements().First(i => i.Name.LocalName == "link").Value,
                                  PubDate = Convert.ToDateTime(item.Elements().First(i => i.Name.LocalName == "pubDate").Value, culture),
                                  PublishDate = Convert.ToDateTime(item.Elements().First(i => i.Name.LocalName == "pubDate").Value, culture).ToString("dd-MMM-yyyy"),
                                  Title = item.Elements().First(i => i.Name.LocalName == "title").Value,
                                  FeedType = (item.Elements().First(i => i.Name.LocalName == "link").Value).ToLowerInvariant().Contains("blog") ? "Blog" : (item.Elements().First(i => i.Name.LocalName == "link").Value).ToLowerInvariant().Contains("news") ? "News" : "Article",
                                  Author = item.Elements().First(i => i.Name.LocalName == "author").Value
                              };

                return await Task.FromResult(entries.OrderByDescending(o => o.PubDate).ToList());
            }
            catch
            {
                List<Feed> feeds = new List<Feed>();
                Feed feed = new Feed();
                feeds.Add(feed);
                return await Task.FromResult(feeds);
            }
        }
    }
}

We have added the business logic for getting the latest post details from C# Corner RSS feeds.

We can create a new razor component “FetchFeeds” under the “Pages” folder.

FetchFeeds

Like the traditional razor views in classic MVC applications, we can add client-side and server-side logic inside the razor component.

FetchFeeds.razor

@page "/fetchfeeds"

@using BlazorSample.Data
@inject RssFeedService FeedService

<h1>C# Corner RSS Feeds</h1>

<p>Getting latest post details from C# Corner RSS Feeds</p>
@if (feeds == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Title</th>
                <th>Post Type</th>
                <th>Published Date</th>
                <th>Author</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var feed in feeds)
            {
                <tr>
                    <td><NavLink [email protected] target="_blank">@feed.Title</NavLink></td>
                    <td>@feed.FeedType</td>
                    <td>@feed.PublishDate</td>
                    <td>@feed.Author</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    List<Feed> feeds;
    protected override async Task OnInitializedAsync()
    {
        feeds = await FeedService.GetFeedsAsyc();
    }
}

We can add the routing for the FetchFeeds component inside the shared component NavMenu under the “Shared” folder.

We have not yet registered the RssFeedService inside the startup class. It is deliberate. Anyway, we can run the application and see, what will happen now.

 RssFeedService

We can click the “C# Corner Posts” menu link and see, what is happening. You can now notice that our component will not be loaded successfully. You can check the developer console and will see the below error message.

Developer console

We have not received a detailed error message in the console. We must enable the detailed error for circuit options in the Startup class.

Startup class

We can run the application and click the menu again.

Run application

This time, we have got the exact error message as we have not yet registered the “RssFeedService”. We can register this service inside the startup class.

Exact error message

We can run the application and click the menu again.

Menu again

We have now successfully fetched the recent post details from C# Corner RSS feeds.

Conclusion

In this post, we have seen how to create a simple Blazor server app using .NET Core 3.0 SDK with the default Blazor template. We have created a service for getting the latest post details from C# Corner RSS feeds and showed the data on a razor component. Microsoft continuously evolving in Blazor development and we can expect more exciting features in the coming days. This is a very basic application. I will try to create more interesting applications on Blazor and will publish the details again. Please do not hesitate to give your valuable feedback so that, I can improve my upcoming articles.


Similar Articles