Creating a new ASP.NET Core Application Project and Setting Up Asp.Net Core Identity

Creating Asp.Net Core Web Api Project

Create a new Asp.Net Core Web Application and name it whatever name you want, but for me I will name my project as PayrollApp.Api since I plan to create a payroll application.

Then select Api for project template and leave Authentication to no Authentication.

Advertisements

Building Asp.Net Core Database and Implementing Asp.Net Core Identity

In the solution explorer add a new folder and call it Data. Inside the Data folder add new folder and name it Entities.

Inside the Entities folder add a new class and call it User.

The User class will inherit IdentityUser and it will have properties of FirstName and LastName.

using Microsoft.AspNetCore.Identity;

namespace PayrollApp.Api.Data.Entities
{
    public class User : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Then inside the Data folder add a new class and call it PayrollContext or whatever name you want.

PayrollContext will inherit IdentityDbContext. This class will be responsible for the communication of our application and the database, but to make it work we need to pass some configurations to our base class.

Create a constructor for our PayrollContext that will accept a DbContextOptions then we will pass it to our base class which is the IdentityDbContext.

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using PayrollApp.Api.Data.Entities;

namespace PayrollApp.Api.Data
{
    public class PayrollContext : IdentityDbContext<User>
    {
        public PayrollContext(DbContextOptions<PayrollContext> options) :base(options)
        {
        }
    }
}

To setup the connection string for our database. Open appsettings.json then add a property for our connection string.

If you are not sure on what data source to use or what SQL Server installed in your machine. You can click View -> SQL Server Object Explorer. Then it will show you the list of SQL Server you have.

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=PayrollDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Open Startup.cs then update the ConfigureServices method to register our PayrollContext as a service. You probably get some errors. You can fix it by adding the needed dependency.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<PayrollContext>(options => options
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<PayrollContext>()
                .AddDefaultTokenProviders();
            services.AddAuthentication().AddJwtBearer();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

Then update Configure method to enable the use of Authentication in our application.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseMvc();
        }

Open a command prompt then navigate to root directory of your project. You can easily get to root directory of your project by doing a right click to your project name in solution explorer then select Open Folder in File Explorer. Copy the directory then go to command prompt type cd then paste your directory and press enter.

cd C:\Users\Alex\source\repos\PayrollApp.Api\PayrollApp.Api

Then let’s add a migration build your application then go to command prompt and execute add migration command. Let’s name this migration as InitialDb.

dotnet ef migrations add InitialDb

If you are not familiar with migrations. Migration is file with a sql command to update a database schema and apply new changes in an existing database.

Now update the database with our current migration by executing the update database command in the command prompt.

dotnet ef database update
Advertisements

In the next article How to Seed Users and Roles in Asp.Net Core I will show you how to seed data for users and roles.

Advertisements

Related Articles:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s