Category Archives: ASP.NET Core

[EN] How to populate database in ASP.NET Core Web Api

When we create our app it’s good to have some data in a database at some point, for example test user accounts or other values if we want to test something. How to populate database at the start of application if the database is empty?

First we need to create new class in our project. Let’s see how to do it on example.

I want to seed the database with test user with admin role, because I want to test loging functionality.

Here’s my class with Seed method.

What it does, it just checks if user „TestAdminUser” and role „Admin” exist in the database. If not it adds them and assigns role and claim to the user. If you are wondering what is User class, I have user class defined which is derived from IdentityUser class (Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser), so it’s IdentityUser class with additional properties.

ELPIdentityInitializer class is not complicated, but we can add here more data. The question is how to load this data and when? As you probably guess, the good place is Startup class and Configure method, because it will be called only once at the start of application. To achieve our goal we need to add another parameter to this method. In my case it will be parameter of type ELPIdentityInitializer. In the body of Configure method, at the end (after UseMvc() method call) we need to execute Seed method from our initializer. This method is awaitable, so we can just wait for completion, because we don’t want to change Configure method to be asynchronous.

Additionally we need to register our initializer class in the service collection, because without it we will see an error while resolving class. To do it let’s add this line of code to the ConfigureServices method in Startup class.

I used AddTransient method here. It means service is created each time it is requested, but it’s not important here. Our service is requested only once at the beginning. BTW Transient lifetime works best for lightweight and stateless services.

After these few steps we should see result of our work which is populated database, in this case Users table.


[EN] How to read data from appsettings.json in ASP.NET Core Web Api

In my previous post about token authentication in ASP.NET Core Web Api I mentioned that is not a good practice to hardcode strings in controller or Startup class, especially if we want to put some sensitive data like key for SigningCredentials or connection string to database or configuration parameters. How to avoid it? We can add all strings to configuration file. In ASP.NET Core we have appsettings.json file which is the right place to put these kind of data. It looks like this by default in Web Api project

ok let’s say we want to add few parameters here, for example data to generate token (in my previous post you can read about generating token) in CreateToken method in one of my Controllers – LoginController.  Here is the method we want to modify.

We want in this case to read issuer and audience from config file, the same with „SuperSecretKey” to generate SymmetricSecurityKey. First we need to add these data to appsettings.json.

Then we need to modify the LoginController where CreateToken method is located.

We need to use IConfigurationRoot object to read data from config file. Let’s add it as private field and inject it in controller.

Now it’s time to replace hardcoded strings in CreteToken method.

Unfortunately that’s not all. It will not work. There’s one step we need to do.  In Startup class we need to register IConfigurationRoot object as a singleton. There’s property called Configuration by default

and we need to add this line of code to ConfigureServices method

That’s all. Since we have known about appsettings.json file it’s good to use it.

[EN] Token authentication in ASP.NET Core Web Api

In the previous post I showed how to implement cookie authentication in ASP.NET Core Web Api, this time I want to show you how to implement token authentication using JWT token. I strongly recommend you to read my previous post about cookie authentication, because it will be simplier to understand, besides source code showed below have some parts described in the previous post.

JWT structure

JWT stands for JSON Web Token. It is small, self-contained JSON. It contains credentials, claims and other information.

JWT consist of header, payload and signature.

Header contains algorithm for JWT and type of token.

Payload contains information that the server can use, e.g. user name, e-mail.

Signature is a secret key generated by server.
The goal is to send token to a client and the client will send it with every request back to the server to guarantee it’s rights. All information in token is encoded in Base64.


Here is a sample of encoded token

Useful web page for decoding JWT tokens is I recommend you to check it.

To better understand token authentication, take a look at the image below.


Client sends credentials, server validates them and returns signed JWT token
to be able to validate it later. Client have to include untouched JWT with every call. It can decode header and payload, but not signature. Only server can decode signature, because the secret is never shared.


We know theory, now it’s time to look into code.
Let’s implement method in controller responsible for generating token, but first it should validate user credentials. In the previous post I used SignInManager class for signin, but this time we don’t want this, because it will generate a cookie. We just want to validate user credentials without a cookie. We can use for it PasswordHasher class. I want to have cleaner code, so I added method for validation in UserService class and UserService is used in LoginController. Here is my UserService with added VerifyHashedPassword method that uses IPasswordHasher

As you can see here are additional methods: GetClaims and GetUserByUsername. GetClaims method will be used to get all information about user and GetUserByUsername finds user by username.
Next it’s time to use these methods in LoginController. Here it is, ready and working create token method.

First we need to find user by username. If the user is found then we can verify password hash. If credentials are good we create the token (BTW we need to add package System.IdentityModel.Tokens.Jwt first).

Then we create claims for user with all necessary informations, key and credentials. Key used to create SymmetricSecurityKey shouldn’t be hardcoded like this. It’s good to move it to configuration file, but I don’t want to complicate this example. Next we create JwtSecurityToken. Issuer and audience is our website that will accept this token. Expires tells how long token is valid.

Now we can test it. Hit f5, open Postman and Send a request.


As you can see we get token in response to our request. It means we did it correctly.

Another thing to do is validating token send by a client.

In Startup class we need to use middleware for security token. Add few lines of code to Configuration method before UserMvc method call. We need to add also Microsoft.AspNetCore.Authentication.JwtBearer package.

TokenValidationParameters should be the same like in create token method. These strings should be also moved to configuration file.

Let’s test it. For example I have EventsController that contains Get method which returns all events, but only for authorized users. If we try to get events we will get 401 Unauthorized error.


In this case we need to get token we generated before while testing create token method and put it in a request header with Key: Authorization and Value: bearer <token>. This time we should get status code 200. It means we have implemented token authentication in ASP.NET Core Web Api successfully.


If you want to take a look at the source code it is available in my Github repo.

[EN] Cookie authentication in ASP.NET Core Web Api

This time I want to focus on user authentication. In APIs we can use different methods for user authentication like:

-cookie Authentication

-basic Authentication (not recommended, slow and insecure)

-token Authentication

In this post I want to show you how to implement cookie authentication in ASP.NET Core Web API.

First make sure you have installed Microsoft.AspNetCore.Identity.EntityFrameworkCore NuGet package in your project. Then let’s modify model a little bit.

Create User class derived from IdentityUser.

Next modify Context class. Our Context should be derived from IdentityDbContext<User> class. If your Context is derived from DbContext class, you need to change it. IdentityContext helps us to create all tables needed for user like Roles, Claims, Tokens, etc.

After these modifications, add another migration via Package Manager Console (type Add-Migration migrationName) and update database by Update-Database command. If you don’t know how to perform code first migrations take a look at one of my previous post.

If we have database ready, we can focus on our API project. In Startup.cs class in ConfigureServices method we need to add identity to services by adding this line of code:

where ELPContext is your app context and User is user class derived from IdentityUser.

That’s not all, we need to add more code, to specify how Identity should work. There’s a small problem with ASP.NET Core WebApi, when you call method that needs authorization you can get 404 Not Found Error instead of 401 Unauthorized. It’s because of default redirection to Account/Login page which can be helpful in ASP.NET MVC project but not in Web API. To handle it we need to set up application cookie events. Events allow us to override things that the IdentitySystem does. Add this code after AddItentity method call.

In the Configure method in Startup class we need to add another line of code before calling app.UseMvc() method:

We have configured our project, so let’s implement controller with register and login methods. I prefer to avoid logic in Controllers and use only services, so first we need to create UserService. This is my UserService for now.

I use UserManager and SigninManager that come from Microsoft.AspNetCore.Identiy namespace. These managers do a lot for us.

When we have service it’s time to use it in Controller.

We have two methods Register and SignIn. It’s time to test it. Hit F5, start your API and open Postman (If you don’t know what is Postman go to my previous post where I mentioned about it).

In Postman pick Post method call, add body which is raw JSON and hit Send. You should see success and status 200 like on image below.


To test Signin method, repeat above steps. You can see in the result in the Cookies tab there’s  cookie provided by ASpNetCore.Identity.Applcation. It contains information about the user. If you close the Postman or browser you have to re-authenticate. The cookie passed back and forth is the thing that going to know what the user is.


Next time I will show you how to implement Token based authentication which is recommended method of authentication 😉

If you want to take a look at the source code it is available in my Github repo.

[EN] Calling ASP.NET Core WebApi from angular app

In the last post I showed how to create service in Angular, now it’s time to try call ASP.NET Core webApi from it.
I created Login controller in my ASP.NET Core WebApi project which contains SignIn method. I want to execute it. I don’t have completed implementation so far, I want only to test if it works. As you see it is HttpPost method and it returns message with current date and status – true.

SignIn method gets UserDto as parameter and it’s important to add [FromBody] attribute, if we want to deserialize json object properly. Let’s start our webApi and try to call it from angular app. It will not work if you didn’t configure WebApi properly to talk with other app. You will see HTTP 415 unsupported media type error everytime you call api. It took me a while to figure it out why it didn’t work, but finally I have found a solution.

Asp.Net Core WebApi configuration

To be able to call our API with success, there is small change in the configuration needed. In Startup class we need to modify a little bit Configure method. Here is default Configure method in ASP.NET Core project

The solution is to configure CORS. There is only one line of code needed. It has to be added before calling UseMvc method.

What is CORS?

It is Cross Origin Resource Sharing. It allows web page to make requests to another domain. We need to enable CORS, because if we have two applications in this case:
– http://localhost:63698/  – backend
– http://localhost:4200/ – frontend
These are two different ports and request doesn’t work correctly without using CORS.
It can be dangerous of course, because we can allow to make requests from another malicious site, but we can specify to use CORS only from the specific origin, from our site, e.g. http://localhost:4200/. In addition CORS builder has a fluent api, so we can add chain of methods, e.g. AllowAnyHeader() or AllowAnyMethod() or we can specify accepted headers. Let’s try to test our app. Here’s my login form. I typed login data and I clicked Login. Let’s see what is in console output.

1 2Yeah it works! This time I used dev console built in Chrome to check result of my request, but there are few other alternatives I want to share with you. For sure there will be a lot of cases when you want to trace your requests in detail during project development. I can recommend you two tools that I use. The first one is Fiddler from Telerik and the second one is Postman. These tools allows you to create requests and inspect them. Let’s take a quick look on Fiddler.


It is desktop application where you can for example use filters to inspect only specific addresses, compose requests and even more.
Postman is desktop application too, but not only. It is also available as extension for Chrome browser. Postman doesn’t scan your network communication. It only allows to create requests and see results, but it is very nice. It allows to save created requests in files.


It is good to know these tools exist, because sooner or later you will find them necessary for daily work.

[EN] How to add Autofac container to ASP.NET Core app?

I created few projects in my solution. I have models, services, tests and webApi project. I added LoginController which uses Services, but it uses it by interfaces. I need to use dependency injection to resolve it for me. I decided to add Autofac. It is IoC container which allow us to register all types and it’s implementations, to inject specific types for us. In the last year I wrote post how to add Autofac to ASP.NET MVC app, but post is in Polish and adding Autofac to .NET Core app is slighty different than the last time.

First step to add Autofac to our project is to download nuget package Autofac.Extensions.DependencyInjection.


Next step is to register all types from assemblies. We need to do it for each assembly (install Autofac too). For example I have ELP.Model, ELP.Service, ELP.WebApi projects and I want to register all types from them. To do it let’s start from ELP.Service project. I prefer to add new interface to it. Just empty interface to determine assembly.

Add also new class derived from Autofac.Module class and override Load method.

As you see the interface is only to get type info from it to get all assemblies and register it in the container. We need to repeat these steps for each project (in my case ELP.Model, ELP.WebApi). This method is very helpful, because every type will be registered automatically without our attention. When we add new interface and class that implements it, no action is required. Autofac does all for us!

Ok if we have modules, it’s time to modify Startup class a little bit.
Add new property ApplicationContainer of IContainer type. Then Create Container builder in ConfigureServices method and register all modules in it, then build and return result in ApplicationContainer. Take a look at my Startup class below.

That’s it. You can ask what if I have few types that implements one interface? How Autofac handles it? It registers the newest one, but maybe there will be a situation when you want to register specific type, then you can do it like this

If you want to use Autofac in you applications I recommend you to take a look at the documentation, where you can read more about it.

[EN] Entity Framework Core – Code First migrations

In this post I want to show you how to create new database using Entity Framework Core – Code First migrations approach.


I have project ELP.Model in which I defined few entities. I want to create database from it. It is approach called Code First. This is how looks one of my entity

To be able to enable migration and create database, we need to create Context. My Context Class looks like this

We need to install few packages before we start with actual migration.

To do it, open Package Manager Console (In VS Tools-> Nuget Package Manager -> Package Manager Console) set Default Project to your target project and install packages. Make sure to install the newest versions or the same versions for all.

To enable migrations in our project first we need to type in the same console Add-Migration MigrationName

and here is surprise. Not so easy man. I missed something. Yes exactly, we need to add implementation of IDbContextFactory<ELPContext>


This class should look like this:

Another Try to Add Migration and … another error…


What da… !? It looks like it is an issue in EF Core v 1.1.0. Work around for it is to change version to 1.0 :/ To do it we need to modify TargetFramework in csproj file from netcoreapp1.1 to netcoreapp1.0



Another try

Uff now everything works fine.


Take a look into Solution Explorer. Here we have new classes and Migrations folder.


The last step is to execute Update-Database command in Package Manager Console.

Fortunately this time it worked for me in first try. I didn’t expect it will be so easy 😉

To verify it, open SQL Server Object Explorer and check it. It should create new database.


Yeah, we have created database, nice. Now we can add something to it 🙂

[EN] How to mock DbSet in Entity Framework


duck as mock

In my project ELP I decided to start with core implementation of backend side. I started with service for sign in and register user accounts. I use TDD approach, so I create test with expected result that fails at the beginning and then I implement code to pass this test.

I created MembershipService in my project that is responsible for creating accounts, validating, etc. This service uses other services like UserService for getting users from database or UserRoleService for getting user roles. Services use context, (BTW I rejected using repository pattern, maybe I will describe more about it in the future) and context contains DbSets.

First problem that you can meet is how to mock this thing?

Let’s see how to write a test for method GetUserByUsername.

This is my test. I use xUnit testing framework and Moq for mocking. If you want to use it as I, you need to install it from Nuget Packages manager.

As you see I created list with one user and I want to pass it to my context, It will act like data get from database. First we need to create our DbSet for Users. I have little helper method for it. It is generic, so you can use it too.

Ok, so first test we have completed, but there’s one more thing that I wanted to share with you.

Let’s get back to my service that I mentioned before – MembershipService. I’d like to test CreateUser method which at the end adds user entity to User’s DbSet. Problem is with verifying it if you use mocks. If you check User’s DbSet from Context class there’s nothing in it. Null. And here comes Verify method from Moq framework that helps.

Here are 3 lines of code from my testing method, it executes CreateUserMethod, so I expect User’s DbSet will contain one item and UserRole’s DbSet will contain two items.

With help of Verify method result is as expected and test is green.

If you want to read more about testing Entity Framework you can go to

[EN] How to create ASP.NET Core project using Visual Studio 2017

In this post I would like to show you how to create ASP.NET Core project using Visual Studio 2017. I’m using VS Community RC edition, but it’s not so important, you can use different edition. So, let’s create new empty solution and then add new Project.


I want to create ASP.NET Core Web API project. Let’s choose correct template then.


You will see new window where you can choose ASP.NET Core Template. I want to create Web API so I’m choosing it. You can choose authentication on the right hand side (Work or School Accounts or Windows Authentication), but I don’t want it. There’s also one very interesting feature here, look at the bottom of this window – there’s option to enable Docker support – WOW, but we will take a look at it maybe later 🙂 Yes, docker is also a thing that I want to learn about in practice.


Ok and project is created. It’s good to test our app if everything is ok. Push F5 and check. You should see new browser tab which displays:


Don’t worry, it means it’s fine 🙂 Project is ready, we can start to work on our API.