Get started with ASP.NET Core Blazor

Get started with ASP.NET Core Blazor

Get started with ASP.NET Core Blazor. Explore ASP.NET Core Blazor, a way to build interactive client-side web UI with .NET in an ASP.NET Core app. This is a get started tutorial on Blazor framework of ASP.NET Core 3.1

Get started with Blazor:

  1. Install the .NET Core 3.1 SDK.

  2. Optionally install the Blazor WebAssembly template:

    dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.1.0-preview4.19579.2
    
    
  3. Follow the guidance for your choice of tooling:

    • Visual Studio
    • Visual Studio Code
    • Visual Studio for Mac
    • .NET Core CLI

3.1. Visual Studio

1. Install Visual Studio 16.4 or later with the ASP.NET and web development workload.

2. Create a new project.

3. Select Blazor App. Select Next.

4. Provide a project name in the Project name field or accept the default project name. Confirm the Location entry is correct or provide a location for the project. Select Create.

5. For a Blazor WebAssembly experience, choose the Blazor WebAssembly App template. For a Blazor Server experience, choose the Blazor Server App template. Select Create. For information on the two Blazor hosting models, Blazor Server and Blazor WebAssembly, see ASP.NET Core Blazor hosting models.

6. Press Ctrl+F5 to run the app.

Note: If you installed the Blazor Visual Studio extension for a prior preview release of ASP.NET Core Blazor (Preview 6 or earlier), you can uninstall the extension. Installing the Blazor templates in a command shell is now sufficient to surface the templates in Visual Studio.

3.2. Visual Studio Code

1. Install Visual Studio Code.

2. Install the latest C# for Visual Studio Code extension.

3. For a Blazor WebAssembly experience, execute the following command in a command shell:

```
dotnet new blazorwasm -o WebApplication1

```

For a Blazor Server experience, execute the following command in a command shell:

```
dotnet new blazorserver -o WebApplication1

```

For information on the two Blazor hosting models, Blazor Server and Blazor WebAssembly, see ASP.NET Core Blazor hosting models.

4. Open the WebApplication1 folder in Visual Studio Code.

5. For a Blazor Server project, the IDE requests that you add assets to build and debug the project. Select Yes.

6. If using a Blazor Server app, run the app using the Visual Studio Code debugger. If using a Blazor WebAssembly app, execute dotnet run from the app's project folder.

7. In a browser, navigate to https://localhost:5001.

3.3. Visual Studio for Mac

1. Install Visual Studio for Mac.

2. Select File > New Solution or create a New Project.

3. In the sidebar, select .NET Core > App.

4. Select the Blazor Server App template. Only the Blazor Server template is available in Visual Studio for Mac at this time. For a Blazor WebAssembly experience, follow the instructions on the .NET Core CLI tab. After selecting the Blazor Server template, select Next. For information on the two Blazor hosting models, Blazor Server and Blazor WebAssembly, .

5. Set the Target Framework to .NET Core 3.1 and select Next.

6. In the Project Name field, name the app WebApplication1. Select Create.

7. Select Run > Run Without Debugging to run the app without the debugger. Run the app with Start Debugging to run the app with the debugger.

```
If a prompt appears to trust the development certificate, trust the certificate and continue.

```

3.4. NET Core CLI

For a Blazor WebAssembly experience, execute the following commands in a command shell:

```
dotnet new blazorwasm -o WebApplication1
cd WebApplication1
dotnet run

```

For a Blazor Server experience, execute the following commands in a command shell:

```
dotnet new blazorserver -o WebApplication1
cd WebApplication1
dotnet run

```

For information on the two Blazor hosting models, Blazor Server and Blazor WebAssembly, .

In a browser, navigate to https://localhost:5001.


Multiple pages are available from tabs in the sidebar:

  • Home
  • Counter
  • Fetch data

On the Counter page, select the Click me button to increment the counter without a page refresh. Incrementing a counter in a webpage normally requires writing JavaScript, but with Blazor you can use C#.

Pages/Counter.razor:

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

A request for /counter in the browser, as specified by the @page directive at the top, causes the Counter component to render its content. Components render into an in-memory representation of the render tree that can then be used to update the UI in a flexible and efficient way.

Each time the Click me button is selected:

  • The onclick event is fired.
  • The IncrementCount method is called.
  • The currentCount is incremented.
  • The component is rendered again.

The runtime compares the new content to the previous content and only applies the changed content to the Document Object Model (DOM).

Add a component to another component using HTML syntax. For example, add the Counter component to the app's homepage by adding a <Counter /> element to the Index component.

Pages/Index.razor:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<Counter />

Run the app. The homepage has its own counter provided by the Counter component.

Component parameters are specified using attributes or child content, which allow you to set properties on the child component. To add a parameter to the Counter component, update the component's @code block:

  • Add a public property for IncrementAmount with a [Parameter] attribute.
  • Change the IncrementCount method to use the IncrementAmount when increasing the value of currentCount.

Pages/Counter.razor:

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    [Parameter]
    public int IncrementAmount { get; set; } = 1;

    private void IncrementCount()
    {
        currentCount += IncrementAmount;
    }
}

Specify the IncrementAmount in the Index component's <Counter> element using an attribute.

Pages/Index.razor:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<Counter IncrementAmount="10" />

Run the app. The Index component has its own counter that increments by ten each time the Click me button is selected. The Counter component (Counter.razor) at /counter continues to increment by one.

Create CRUD App with ASP.NET Core, Blazor WebAssembly, Web API, VScode

Create CRUD App with ASP.NET Core, Blazor WebAssembly, Web API, VScode

In this Blazor WebAssembly tutorial, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Visual Studio, .NET Core 3, Entity Framework and Web API. Blazor is a new framework introduced by Microsoft. How to build CRUD (CREATE, READ, UPDATE & DELETE) App using the Blazor SPA Framework, Entity Framework and SQL server. How to create a web application using Blazor with the help of Entity Framework Core. CRUD Using Blazor And Entity Framework Core in ASP.NET Core 3.0.

Blazor CRUD App tutorial - SPA Framework for .NET developers

This video tutorial is about to create advance crud (CREATE, READ, UPDATE & DELETE) application using the blazor spa framework, entity framework, and SQL server.

Code: https://github.com/dotnettrainingacademy/Blazor-CRUD

Blazor CRUD - Make a CRUD app with Blazor and Entity Framework Core

In this video we will make a Blazor WebAssembly app that communicates with an ASP.NET Core Web API to read and store data in a database.

CRUD Using Blazor And Entity Framework Core in ASP.NET Core.

How to create a web application using Blazor with the help of Entity Framework Core.
CRUD Using Blazor And Entity Framework Core in ASP.NET Core 3.0.

AspNet Core Blazor WebAssembly - CRUD Create a simple CRUD application for ASP.NET Core Blazor using Visual Studio 2019, .NET Core 3, Entity Framework and Web API

Introduction

In this article, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Visual Studio 2019, .NET Core 3, Entity Framework and Web API. Blazor is a new framework introduced by Microsoft.

Blazor:

Blazor has two kind of Application development on is Blazor Client app which is in preview now and also Blazor Server app. Blazor Client app runs in WebAssembly, Blazor Server app runs using SignalR. Blazor apps can be created using C#, Razor, and HTML instead of JavaScript Blazor WebAssembly Works in all modern web browsers also in mobile browsers. The main advantage we have in Blazor is C# code files and Razor files are compiled into .NET assemblies. Blazor has reusable components, Blazor Component can be as a page,Dialog or Entry Form, Blazor also used to create Single Page Applications. Blazor is used to create two kind of applications one is Blazor Client-Side App and another one is Blazor Server Side APP.here we will see some more details on

Blazor Client App:

  • Blazor Client Side is still in preview.
  • Blazor Client side uses Web Assembly
  • In Blazor Client Side all the.Net dll’s will be downloaded to browser. The download size might be bigger and might be some time delay in loading due to all downloads happen in client browser.
  • No need of server-side dependency for the Blazor Client-side application.
  • All similer kind of JavaScript coding can be done in Blazor Client app and it’s not really needed to use of JavaScript Interop.
  • It can be deployed as Static site which means it support offline as well.
  • Debugging is more complicated than Blazor Server side.
  • In client side leaking of database connectivity and also all the application code will be in client side and security level is not much good.

Blazor Server App:

  • All the Component Process will be happening in the Server.
  • Blazor Server uses SignlR Connection to connect from the web server to browsers.
  • In client side leaking of database connectivity is not happen as all will be happen in Server.
  • All the form connection will be happening in the server side and no dll’s download to the client side.As all the dll’s will be in web server.
  • Small download size and faster loading time than the Blazor Client App.
  • We can use .Net core in Blazor server side.
  • Debugging is great in Blazor Server Side.
  • Runs in any web browser as no need of WebAssemble.
  • Each browser session is open with SignalR connection.

Background

Prerequisites

Using the code

Step 1 - Create a database and a table

We will be using our SQL Server database for our WEB API and EF. First, we create a database named CustDB and a table as CustDB. Here is the SQL script to create a database table and sample record insert query in our table. Run the query given below in your local SQL Server to create a database and a table to be used in our project.

USE MASTER       
GO       
       
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB       
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'CustDB' )       
DROP DATABASE CustDB       
GO       
       
CREATE DATABASE CustDB       
GO       
       
USE CustDB       
GO       
       
       
-- 1) //////////// Customer Masters    

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'CustomerMaster' )       
DROP TABLE CustomerMaster       
GO       
       
CREATE TABLE [dbo].[CustomerMaster](       
        [CustCd] [varchar](20) NOT NULL ,         
        [CustName] [varchar](100) NOT NULL,          
        [Email]  [nvarchar](100) NOT NULL,        
        [PhoneNo] [varchar](100) NOT NULL,           
        [InsertBy] [varchar](100) NOT NULL,   
        PRIMARY KEY (CustCd)  
)       
       
-- insert sample data to Student Master table       
INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C001','ACompany','[email protected]','01000007860','Shanun')       
       
INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C002','BCompany','[email protected]','0100000001','Afraz')  

INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C003','CCompany','[email protected]','01000000002','Afreen')  

INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C004','DCompany','[email protected]','01000001004','Asha')  
            
     select * from CustomerMaster

Step 2 - Create ASP.NET Core Blazor Server Application

After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. Click New >> Project.

Click Create a new project to create our ASP.NET Core Blazor Application.


Select Blazor App and click Next button.

Select your project folder and Enter your Project name and then click Create button.

Select Blazor Server App

After creating ASP.NET Core Blazor Server Application, wait for a few seconds. You will see the below structure in solution explorer.

In the Data folder we can add all our Model, DBContext Class, Services and Controller, we will see that in this article.

In the Pages folder we can add all our component files.component file all should have the .razor extension with the file name.

In the Shared folder we can add all left menu form NavMenu.razor file and change the main content from the MainLayout.razor file.

In the _Imports.razor file we can see all set of imports has been added inorder to used in all component pages.

In the App.razor file we will add our main component to be displayed by default when run in browser.Appsertings.json can be used to add the connection string.

Startup.cs file is important file where we add all our endpoints example like Controller end points, HTTP Client,add services and dbcontext to be used in startup Configuration method.

Run to test the application

When we run the application, we can see that the left side has navigation and the right side contains the data. We can see as the default sample pages and menus will be displayed in our Blazor web site. We can use the pages or remove it and start with our own page.

Debug in component

The big advantage of Blazor is as we can use our C# code in razor and also keep the break point in the code part and in browser we can debug and check for all our business logic is working properly and to trace any kind error easily with break point.

For this we take our existing Counter component page.

This is the actual code of our Counter page as in the counter we can see there is button and in button click called the method to perform the increment.

We add one more button and in button click event we call the method and bind the name in our component page.
In html design part we add the below code.

<h1>My Blozor Code part</h1>
    My Name is : @myName   <br />
 <button @onclick="ClickMe">Click Me</button>

Note that : all the C# code part and functions can be written under the @code {} part.
We add the method ClickMe and declare property to bind the name inside the @Code part

[Parameter]
    public string myName { get; set; }
private void ClickMe()
    {
        myName="Shanu";
    }

The complete Coutner Component page code will be like this.

Now lets add the break point in our ClickMe method


Run the program and open the counter page.

We can see as when we click on the Click Me button we can debug and check for the value from the breakpoint we placed.

Now lets see on performing CRUD operation using EF and Web API in Bloazor.

Step 3 - Using Entity Framework

To use the Entity Framework in our Blazor application we need to install the below packages

Install the Packages

Microsoft.EntityFrameworkCore.SqlServer - For using EF and SQL Server

Microsoft.EntityFrameworkCore.Tools - For using EF and SQL Server

Microsoft.AspNetCore.Blazor.HTTTPClient - For communicating WEB API from our Blazor Component.

First we will add the Microsoft.EntityFrameworkCore.SqlServer ,For this right click on the project and click on Manage NuGet Packages.

Search for all the three packages and install all the needed packages like below image.

Add DB Connection string

Open the appsetting file and add the connection string like below image.

"ConnectionStrings": {

    "DefaultConnection": "Server= DBServerName;Database=CustDB;user id= SQLID;-password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true"

},


Create Model Class

Next, we need to create the Model class with same as our SQL Table name and also define the property fields similar to our SQL filed name as below.

Right Click the Data Folder and create new class file as “CustomerMaster.cs”

In the class we add the property field name same as our table column names like below code.

[Key]
  public string CustCd { get; set; }
  public string CustName { get; set; }
  public string Email { get; set; }
  public string PhoneNo { get; set; }
 public string InsertBy { get; set; }

Create dbConext Class

Next, we need to create the dbContext class.Right Click the Data Folder and create new class file as “SqlDbContext.cs”

We add the below code in the DbContext class as below in order to add the SQLContext and add the DBset for our CustomerMaster Model.

public class SqlDbContext:DbContext
  {
      public SqlDbContext(DbContextOptions<SqlDbContext> options)
         : base(options)
      {
      }
      public DbSet<BlazorCrudA1.Data.CustomerMaster> CustomerMaster { get; set; }
  }

Adding DbContext in Startup

Adding the DbContext in Startup.cs file ConfigureServices method as below code and also we give the connection string which we used to connect to SQLServer and DB.

services.AddDbContext<SqlDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Note that in the ConfigureServices method we can also see as the weatherforecast service has been added.if we create an new service then we need to add the service in like below code in ConfigureServices method.

services.AddSingleton<WeatherForecastService>();

Creating Web API for CRUD operation

To create our WEB API Controller, right-click Controllers folder. Click Add New Controller.

Here we will be using Scaffold method to create our WEB API. We select API Controller with actions, using Entity Framework and click Add button.

Select our Model class and DBContext class and click Add button.

Our WEB API with Get/Post/Put and Delete method for performing the CRUD operation will be automatically created and we no need to write any code in Web API now as we have used the Scaffold method for all the actions and methods add with code.

To test Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get /api/CustomerMasters/

Run the program and paste API path to test our output.

If you see this error means then we need to add the endpoints of controller in the Startup.cs file Configure method.
Add the below code in the Configure method in Startup.cs file

endpoints.MapControllers();

we add inside the UseEndpoints like below code in Configure method.

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });

Now run again and check for /api/CustomerMasters/ to see the Json data from our database.

Now we will bind all this WEB API Json result in component.

Working with Client Project

First, we need to add the Razor Component page

Add Razor Component

To add the Razor Component page right click the Pages folder from the Client project. Click on Add >> New Item >> Select Razor Component >> Enter your component name,Here we have given the name as Customerentry.razor

Note all the component file need to have the extentions as .razor.

In Razor Component Page we have 3 parts of code as first is the Import part where we import all the references and models for using in the component, HTML design and data bind part and finally we have the function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in Component page.

Import part

First, we import all the needed support files and references in our Razor View page. Here we have first imported our Model class to be used in our view and also imported HTTPClient for calling the Web API to perform the CRUD operations.

@page "/customerentry"
@using BlazorCrudA1.Data
@using System.Net.Http
@inject HttpClient Http 
@using Microsoft.Extensions.Logging

Register HTTPClient for Server side Blazor

In order to use the HTTPClient in Blazor Server side we need to add the below code in Startup.cs ConfigureServices method.

services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });

            // Server Side Blazor doesn't register HttpClient by default
            if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
            {
                // Setup HttpClient for server side in a client side compatible fashion
                services.AddScoped<HttpClient>(s =>
                {
                    // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.      
                    var uriHelper = s.GetRequiredService<NavigationManager>();
                    return new HttpClient
                    {
                        BaseAddress = new Uri(uriHelper.BaseUri)
                    };
                });
            }

HTML design and data Bind part

Next, we design our Customer Master details page to display the Customer details from the database and created a form to Insert and update the Customer details we also have Delete button to delete the Custoemr records from the database.

For binding in Blazor we use the **@****bind**="@custObj.CustCd" and to call the method using **@****onclick**="@AddNewCustomer"

<h1> ASP.NET Core BLAZOR CRUD demo for Customers</h1>
<hr />
<table width="100%" style="background:#05163D;color:honeydew">
    <tr>
        <td width="20"> </td>
        <td>
            <h2> Add New Customer Details</h2>
        </td>
        <td> </td>
        <td align="right">
            <button class="btn btn-info" @onclick="@AddNewCustomer">Add New Customer</button>
        </td>
        <td width="10"> </td>
    </tr>
    <tr>
        <td colspan="2"></td>
    </tr>
</table>
<hr />
@if (showAddrow == true)
{
    <form>
        <table class="form-group">
            <tr>
                <td>
                    <label for="Name" class="control-label">Customer Code</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.CustCd" />
                </td>
                <td width="20"> </td>
                <td>
                    <label for="Name" class="control-label">Customer Name</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.CustName" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Email" class="control-label">Email</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.Email" />
                </td>
                <td width="20"> </td>
                <td>
                    <label for="Name" class="control-label">Phone</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.PhoneNo" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Name" class="control-label">Insert By</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.InsertBy" />
                </td>
                <td width="20"> </td>
                <td>
                </td>
                <td>
                    <button type="submit" class="btn btn-success" @onclick="@AddCustomer" style="width:220px;">Save</button>
                </td>
            </tr>
        </table>
    </form>
}
<table width="100%" style="background:#0A2464;color:honeydew">
    <tr>
        <td width="20"> </td>
        <td>
            <h2>Customer List</h2>
        </td>

    </tr>
    <tr>
        <td colspan="2"></td>
    </tr>
</table> 

@if (custs == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Customer Code</th>
                <th>Customerr Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Inserted By</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var cust in custs)
            {
                <tr>
                    <td>@cust.CustCd</td>
                    <td>@cust.CustName</td>
                    <td>@cust.Email</td>
                    <td>@cust.PhoneNo</td>
                    <td>@cust.InsertBy</td>
                    <td><button class="btn btn-primary" @onclick="@(async () => await EditCustomer(cust.CustCd))" style="width:110px;">Edit</button></td>

                    <td><button class="btn btn-danger" @onclick="@(async () => await DeleteCustomer(cust.CustCd))">Delete</button></td>
                </tr>

            }
        </tbody>
    </table>
}

Function Part

Function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in Component page.In this Function we create a separate function for Add, Edit and Delete the student details and call the Web API Get,Post,Put and Delete method to perform the CRUD operations and in HTML we call all the function and bind the results.

@code {

    private CustomerMaster[] custs;

    CustomerMaster custObj = new CustomerMaster();

    string ids = "0";
    bool showAddrow = false;

    bool loadFailed;

    protected override async Task OnInitializedAsync()
    {
        ids = "0";
        custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
    }

    void AddNewCustomer()
    {
        ids = "0";
        showAddrow = true;
        custObj = new CustomerMaster();
    }
    // Add New Customer Details Method
    protected async Task AddCustomer()
    {
        if (ids == "0")

        {
            await Http.SendJsonAsync(HttpMethod.Post, "/api/CustomerMasters/", custObj);
            custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
        }
        else
        {
            await Http.SendJsonAsync(HttpMethod.Put, "/api/CustomerMasters/" + custObj.CustCd, custObj);
            custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
        }

        showAddrow = false;
    }
    // Edit Method
    protected async Task EditCustomer(string CustomerID)
    {
        showAddrow = true;

        ids = "1";
        //try
        //{
        loadFailed = false;
        ids = CustomerID.ToString();
        custObj = await Http.GetJsonAsync<CustomerMaster>("/api/CustomerMasters/" + CustomerID);

        string s = custObj.CustCd;

        showAddrow = true;

        //    }
        //catch (Exception ex)
        //{
        //    loadFailed = true;
        //    Logger.LogWarning(ex, "Failed to load product {ProductId}", CustomerID);
        //}
    }
    // Delte Method
    protected async Task DeleteCustomer(string CustomerID)
    {
        showAddrow = false;

        ids = CustomerID.ToString();
        await Http.DeleteAsync("/api/CustomerMasters/" + CustomerID);

        custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
    }

}

Navigation Menu

Now we need to add this newly added CustomerEntry Razor component to our left Navigation. For adding this Open the Shared Folder and open the NavMenu.cshtml page and add the menu.

<li class="nav-item px-3">
            <NavLink class="nav-link" href="CustomerEntry">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Customer Master
            </NavLink>
        </li>

Build and Run the application

Conclusion

Note that when creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. Here we have created table in SQl server and used with Web API you can also do this with Services and also Code First approach, Hope you all like this article. In the next article, we will see more examples to work with Blazor. It's really very cool and awesome to work with Blazor.

Goodbye Javascript! Build an Authenticated Web App in C# with Blazor + ASP.NET Core 3.0

Goodbye Javascript! Build an Authenticated Web App in C# with Blazor + ASP.NET Core 3.0

In this post, you'll see why we say goodbye JavaScript and how to build an Authenticated Web App in C# with Blazor and ASP.NET Core 3.0. Goodbye Javascript! Build an Authenticated Web App in C# with Blazor + ASP.NET Core 3.0

Curious what the experience would be like to trade in Javascript for C# on the front end? You are about to find out!

For many years, Javascript (and it’s child frameworks) have had their run of the DOM (Document Object Model) in a browser, and it took having that scripting knowledge to really manipulate client-side UI. About 2 years ago, all of that changed with the introduction of Web Assembly - which allows compiled languages to be interpreted client-side and is fully supported across all browsers now. Microsoft’s answer to this was the creation of Blazor. Allowing C# developers to build their entire stack in .NET, including UI, was an exciting proposition. For some time Blazor has been in preview but is now included as a general release on September 23rd, 2019 along with the next iteration of .NET Core - version 3.0.

In order to build with Blazor and ASP.NET Core 3.0, you need the following prerequisites installed and ready to go:

Build a Basic Website with ASP.NET Core 3.0 + Blazor

Now that you have your dev environment handy, let’s get familiar with what a basic website walkthrough would be like. There are two ways you can utilize this technology: client-side or server-side Blazor. For this example, the server-side option is the best choice for stability, as client-side Blazor is still new and working on the final release. Stay tuned for that implementation!

First, you’ll need to create a Blazor project. As long as you’ve installed the .NET Core 3.0 SDK, Visual Studio (16.3 or later) will detect that the templates have been installed and surface them to you without the need for any additional extensions. Now it’s time to scaffold your new project. From your parent directory of code repositories, execute the following command:

dotnet new blazorserver -o OktaBlazorAspNetCoreServerSide

Once it’s been run, open up the OktaBlazorAspNetCoreServerSide folder in Visual Studio Code. Once loaded, if you look in the bottom right-hand corner of the IDE you will see a permission request to add assets to the build. Select Yes.

Now that everything has been loaded up, return to your command line/terminal and run the project.

dotnet run

Launch your browser of choice and navigate to https://localhost:5001. You should see a templated website.

NOTE: When you see the app running initially on HTTPS you may get a certificate error. See this blog post to resolve certificates locally.

Add User Authentication your Blazor Web App

ASP.NET Core 3.0 has brought along with it some hefty changes to the libraries and dependencies from previous versions of .NET Core. To get started with using an external OAuth provider, like Okta, there is a NuGet package you need to add to the project. Fire up your command line/terminal window in VS Code and add the Okta .NET SDK:

dotnet add package Okta.Sdk --version 1.4.0

In 3.0, ASP.NET Core ships as part of the .NET Core shared framework. The metapackage that was used for 2.x apps is no longer used. The first line of your project file that references the Web SDK is what pulls in the shared assemblies for ASP.NET Core.

For user authentication with OAuth, there is an additional layer of information you will use, called Open ID Connect (OIDC). While much of handling authentication is baked into the new 3.0 framework, OIDC is not included, so you’ll need to add a quick reference to that.

dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect --version 3.0.0-preview9.19424.4

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you will configure in the next section. Add the following code to the very top of your appsettings.json file, inside of the first brackets, and separate it from the rest of the settings by adding a comma after it.

"Okta": {
    "Issuer": "https://okta.okta.com/oauth2/default",
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}"
  }

Your file should look like this:

NOTE: If necessary, edit the Login redirect URL and update it to include any ports you use to call it. Otherwise you get a 400 Bad Request from Okta. See this documentation to troubleshoot.

Just to make sure everything still can run, go ahead and execute dotnet run again.

Set Up Your Okta Account to handle the ASP.NET Core 3.0 Blazor App

Execute the following steps to configure Okta so that users can register themselves for an account. From the Administrative Dashboard, hover over Users and click Registration Click Enable Registration Save the changes Once you have access to your account you can proceed to the Dashboard using a link like the one below: https://dev-12345.okta.com/admin/dashboard On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application. Then select Web and click Next.

On the Create New Application screen, set the following values:

  • Name: OktaBlazorAspNetCoreServerSide
  • Base URIs: https://localhost:5001/
  • Login redirect URIs: https://localhost:5001/authorization-code/callback

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values:

-Logout redirect URIs: https://localhost:5001/signout-callback-oidc -Initiate login URI: https://localhost:5001/authorization-code/callback

Once you’ve saved those values, scroll down and take note of the ClientID and ClientSecret.

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page.

You will use your Okta account settings to update those values in the appsettings.json file in your project. For an even more secure way to store those values, check out this post if you are using Azure to host your .NET Core app.

Configure Your Blazor App to use Okta as the External Auth Provider

Great! Now that Okta has been configured and is ready to go, there are a few changes that need to be made to the application startup.

Add these using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Logging;

Replace all the code in the ConfigureServices method with the code below.

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<WeatherForecastService>();

    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddOpenIdConnect(options =>
    {
        options.ClientId = Configuration["Okta:ClientId"];
        options.ClientSecret = Configuration["Okta:ClientSecret"];
        options.CallbackPath = "/authorization-code/callback";
        options.Authority = Configuration["Okta:Issuer"];
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters.ValidateIssuer = false;
        options.TokenValidationParameters.NameClaimType = "name";
    })
    .AddCookie();
}

ASP.NET Core 3.0 has new options to configure the services in this file. UseAuthorization has been newly added to 3.0 project templates.

In the Configure() method of your Startup.cs file add this line just before the app.UseEndpoints() method:

//Add Auth to app
app.UseAuthentication();
app.UseAuthorization();

Inside of the app.UseEndpoints object add the MapControllers() as shown.

app.UseEndpoints(endpoints =>
{
    //Add MapControllers to app
    endpoints.MapControllers();
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");
});

In this example, you’ll see there’s a new UseEndpoints method in Startup.cs. This is what enables the new endpoint routing system in ASP.NET Core. All 3.0 project templates use that now. Think of this as a more performant routing system.

NOTE: In the context of Blazor apps, endpoint routing is the more holistic way of handling redirects. This is covered here in depth. Also, see this documentation to learn more about it. Endpoint routing shipped in ASP.NET Core 2.2, but it didn’t become the default in the templates until 3.0.

Now add a new folder at the top level called Controllers to your application. Next, add a new file called LoginController.cs and paste in the following code below:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace BlazorServerWithOkta.Controllers
{
    public class LoginController : Controller
    {
        [HttpGet("Login")]
        public IActionResult Login([FromQuery]string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return LocalRedirect(returnUrl ?? Url.Content("~/"));
            }

            return Challenge();
        }

        [HttpGet("Logout")]
        public async Task<IActionResult> Logout([FromQuery]string returnUrl)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return LocalRedirect(returnUrl ?? Url.Content("~/"));
            }

            await HttpContext.SignOutAsync();

            return LocalRedirect(returnUrl ?? Url.Content("~/"));
        }

        [HttpPost("Logout")]
        [ValidateAntiForgeryToken]
        public IActionResult PostLogout([FromQuery]string returnUrl)
        {
            returnUrl ??= Url.Content("~/");
            returnUrl = Url.IsLocalUrl(returnUrl) ? returnUrl : Url.Content("~/");

            if (User.Identity.IsAuthenticated)
            {
                HttpContext.SignOutAsync();
            }

            return LocalRedirect(returnUrl);
        }

    }
}

This LoginController contains all of the logic we need to do the routing based on the Identity model provided by default. Since the LoginController has been registered by convention via the MapControllers() method you previously added to the Startup file, your Blazor app will know how to reach it.

Add User Login to your Blazor Web App UI

Time to add some user personalization to this app! Go inside the Shared folder and create a new file called LoginDisplay.razor. Paste in the code below:

<AuthorizeView>
    <Authorized>
        <a href="#">Hello, @context.User.Identity.Name!</a>
        <a href="Logout">Logout</a>
    </Authorized>
    <NotAuthorized>
        <a href="Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

You’ve just created your first custom razor view! Let’s use it in the existing app now. Open Shared/MainLayout.razor and add the LoginDisplay view right before the About link as shown below:

<div class="top-row px-4">
    <LoginDisplay />
    <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
</div>

Using <AuthorizeView> is the easiest way to access authentication data, and is useful when you need to display a user’s name. The <AuthorizeView> component exposes a context variable of type AuthenticationState. It’s useful to make the AccessToken returned by the identity provider available to the entire app’s scope. In order to add this state to our app, open App.razor and wrap the HTML you see with <CascadingAuthenticationState> tags at the parent level. Replace all of the HTML with the snippet below to see the completed alteration:

<CascadingValue Name="AccessToken" Value="AccessToken">
    <CascadingAuthenticationState>
        <Router AppAssembly="@typeof(Program).Assembly">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </NotFound>
        </Router>
    </CascadingAuthenticationState>
</CascadingValue>
@code{
    [Parameter] public string AccessToken { get; set; }
}

Test Okta Registration and Login for Your Blazor App

That’s it! To test it out, go back to the command line/terminal and execute dotnet run.

Then navigate to http://localhost:5001 in your browser. Click Login and you should be redirected to the Okta Sign-In Page.

Because you configured your Okta org for self-registration, there should be an option at the bottom of the widget to allow users to register for a new account.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

All of that and not one line of Javascript. The future is looking bright for C#, give it a go with Blazor!

Originally published by Heather Downing at https://developer.okta.com

Building Authenticated Web app with C#, Blazor and ASP.NET Core 3.0

Building Authenticated Web app with C#, Blazor and ASP.NET Core 3.0

Goodbye Javascript! Now, i can Building an Authenticated Web App in C# with Blazor + ASP.NET Core 3.0.

Curious what the experience would be like to trade in Javascript for C# on the front end? You are about to find out!

Table of Contents

  • Build a Basic Website with ASP.NET Core 3.0 + Blazor
  • Add User Authentication your Blazor Web App
  • Set Up Your Okta Account to handle the ASP.NET Core 3.0 Blazor App
  • Configure Your Blazor App to use Okta as the External Auth Provider
  • Add User Login to your Blazor Web App UI
  • Test Okta Registration and Login for Your Blazor App
  • Learn More about ASP.NET Core, Blazor and Authentication

For many years, Javascript (and it’s child frameworks) have had their run of the DOM (Document Object Model) in a browser, and it took having that scripting knowledge to really manipulate client-side UI. About 2 years ago, all of that changed with the introduction of Web Assembly - which allows compiled languages to be interpreted client-side and is fully supported across all browsers now. Microsoft’s answer to this was the creation of Blazor. Allowing C# developers to build their entire stack in .NET, including UI, was an exciting proposition. For some time Blazor has been in preview but is now included as a general release on September 23rd, 2019 along with the next iteration of .NET Core - version 3.0.

In order to build with Blazor and ASP.NET Core 3.0, you need the following prerequisites installed and ready to go:

Build a Basic Website with ASP.NET Core 3.0 + Blazor

Now that you have your dev environment handy, let’s get familiar with what a basic website walkthrough would be like. There are two ways you can utilize this technology: client-side or server-side Blazor. For this example, the server-side option is the best choice for stability, as client-side Blazor is still new and working on the final release. Stay tuned for that implementation!

First, you’ll need to create a Blazor project. To get the latest Blazor project templates to work with Visual Studio or VS Code, simply install them from the command line/terminal from your base repo directory:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19424.4

Visual Studio (16.3 or later) will detect that the templates have been installed and surface them to you without the need for any additional extensions. Now it’s time to scaffold your new project. From your parent directory of code repositories, execute the following command:

dotnet new blazorserver -o OktaBlazorAspNetCoreServerSide

Once it’s been run, open up the OktaBlazorAspNetCoreServerSide folder in Visual Studio Code. Once loaded, if you look in the bottom right-hand corner of the IDE you will see a permission request to add assets to the build. Select Yes.

Now that everything has been loaded up, return to your command line/terminal and run the project.

dotnet run

Launch your browser of choice and navigate to https://localhost:5001. You should see a templated website.

Add User Authentication your Blazor Web App

ASP.NET Core 3.0 has brought along with it some hefty changes to the libraries and dependencies from previous versions of .NET Core. To get started with using an external OAuth provider, like Okta, there is a NuGet package you need to add to the project. Fire up your command line/terminal window in VS Code and add the Okta .NET SDK:

dotnet add package Okta.Sdk --version 1.4.0

In 3.0, ASP.NET Core ships as part of the .NET Core shared framework. The metapackage that was used for 2.x apps is no longer used. The first line of your project file that references the Web SDK is what pulls in the shared assemblies for ASP.NET Core.

For user authentication with OAuth, there is an additional layer of information you will use, called Open ID Connect (OIDC). While much of handling authentication is baked into the new 3.0 framework, OIDC is not included, so you’ll need to add a quick reference to that.

dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect --version 3.0.0-preview9.19424.4

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you will configure in the next section. Add the following code to the very top of your appsettings.json file, inside of the first brackets, and separate it from the rest of the settings by adding a comma after it.

"Okta": {
    "Issuer": "https://okta.okta.com/oauth2/default",
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}"
  }

Your file should look like this:

Just to make sure everything still can run, go ahead and execute dotnet run again.

Set Up Your Okta Account to handle the ASP.NET Core 3.0 Blazor App

Execute the following steps to configure Okta so that users can register themselves for an account.

  1. From the Administrative Dashboard, hover over Users and click Registration
  2. Click Enable Registration
  3. Save the changes

Once you have access to your account you can proceed to the Dashboard using a link like the one below: https://okta.okta.com/admin/dashboard

On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application. Then select Web and click Next.

On the Create New Application screen, set the following values:

  • Name: OktaBlazorAspNetCoreServerSide

  • Base URIs: https://localhost:5001/

  • Login redirect URIs: https://localhost:5001/authorization-code/callback

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values: Logout redirect URIs: https://localhost:5001/signout-callback-oidc Initiate login URI: https://localhost:5001/authorization-code/callback

Once you’ve saved those values, scroll down and take note of the ClientID and ClientSecret.

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page.

You will use your Okta account settings to update those values in the appsettings.json file in your project.

Configure Your Blazor App to use Okta as the External Auth Provider

Great! Now that Okta has been configured and is ready to go, there are a few changes that need to be made to the application startup.

Add these using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;

Replace all the code in the ConfigureServices method with the code below.

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<WeatherForecastService>();
    services.AddAuthorizationCore();
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ClientId = Configuration["okta:ClientId"];
        options.ClientSecret = Configuration["okta:ClientSecret"];
        options.Authority = Configuration["okta:Issuer"];
        options.CallbackPath = "/authorization-code/callback";
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.UseTokenLifetime = false;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name"
        };
    });
}

ASP.NET Core 3.0 has new options to configure the services in this file. UseAuthorization has been newly added to 3.0 project templates.

In the Configure() method of your Startup.cs file add this line just before the app.UseEndpoints() method:

app.UseAuthentication();
app.UseAuthorization();

In this example, you'll see there's a new UseEndpoints method in Startup.cs. This is what enables the new endpoint routing system in ASP.NET Core. All 3.0 project templates use that now. Think of this as a more performant routing system.

NOTE: In the context of Blazor apps, endpoint routing is the more holistic way of handling redirects. This is covered here in depth. Also, see this documentation to learn more about it. Endpoint routing shipped in ASP.NET Core 2.2, but it didn't become the default in the templates until 3.0.

Add User Login to your Blazor Web App UI

Time to add some user personalization to this app! Open Shared/MainLayout.razor and add the following HTML right before the About link.

<AuthorizeView>
<Authorized>
            <a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>
            <a href="Identity/Account/LogOut">Log out</a>
    </Authorized>
    <NotAuthorized>
            <a href="Identity/Account/Register">Register</a>
            <a href="Identity/Account/Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

Using <AuthorizeView> is the easiest way to access authentication data, and is useful when you need to display a user’s name. The <AuthorizeView> component exposes a context variable of type AuthenticationState. In order to add this state to our app, open App.razor and wrap the HTML you see with <CascadingAuthenticationState> tags at the parent level. It should look like this:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        ...
    </Router>
</CascadingAuthenticationState>
Test Okta Registration and Login for Your Blazor App

That’s it! To test it out, go back to the command line/terminal and execute dotnet run.

Then navigate to http://localhost:5001 in your browser. Click Login and you should be redirected to the Okta Sign-In Page.

Because you configured your Okta org for self-registration, there should be an option at the bottom of the widget to allow users to register for a new account.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

All of that and not one line of Javascript. The future is looking bright for C#, give it a go with Blazor!

Thank for reading! Originally published on scotch.io