Saturday, 12 December 2015

Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7


One of the main new features of ASP.NET 5 is unifying the programming model and combining MVC, Web API, and Web Pages in single framework called MVC 6. In previous versions of ASP.NET (MVC 4, and MVC 5) there were overlapping in the features between MVC and Web API frameworks, but the concrete implementation for both frameworks was totally different, with ASP.NET 5 the merging between those different frameworks will make it easier to develop modern web applications/HTTP services and increase code reusability.

The source code for this tutorial is available on GitHub.

Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7

In this post I’ve decided to give ASP.NET 5 – MVC 6 Web API a test drive, I’ll be building a very simple RESTful API from scratch by using MVC 6 Web API and the new Entity Framework 7, so we will learn the following:
  • Using the ASP.NET 5 empty template to build the Web API from scratch.
  • Overview of the new project structure in VS 2015 and how to use the new dependency management tool.
  • Configuring ASP.NET 5 pipeline to add only the components needed for our Web API.
  • Using EF 7 commands and the K Version Manager (KVM) to initialize and apply DB migrations.
To follow along with this post you need to install VS 2015 preview edition or you can provision a virtual machine using Azure Images as they have an Image with VS 2015 preview installed.

Step 1: Creating an empty web project

Open VS 2015 and select New Web Project (ASP.NET Web Application) as the image below, do not forget to set the .NET Framework to 4.5.1. You can name the project “Registration_MVC6WebApi”.
ASPNET5 New project
Now we’ll select the template named “ASP.NET 5 Empty” as the image below, this template is an empty template with no core dependencies on any framework.
MVC 6 Web API Project Template

Step 2: Adding the needed dependencies

Once the project is created you will notice that there is a file named “project.json” this file contains all your project settings along with a section for managing project dependencies on other frameworks/components.
We’ve used to manage packages/dependencies by using NuGet package manager, and you can do this with the new enhanced NuGet package manager tool which ships with VS 2015, but in our case we’ll add all the dependencies using the “project.json” file and benefit from the IntelliSense provided as the image below:
NuGet IntelliSense
So we will add the dependencies needed to configure our Web API, so open file “project.json” and replace the section “dependencies” with the section below:
The use for each dependency we’ve added as the below:
  • Microsoft.AspNet.Server.IIS: We want to host our Web API using IIS, so this package is needed. If you are planning to self-host your Web API then no need to add this package.
  • EntityFramework & EntityFramework.SqlServer: Our data provider for the Web API will be SQL Server. Entity Framework 7 can be configured to work with different data providers and not only relational databases, the data providers supported by EF 7 are: SqlServer, SQLite, AzureTableStorage, and InMemory. More about EF 7 data providers here.
  • EntityFramework.Commands: This package will be used to make the DB migrations command available in our Web API project by using KVM, more about this later in the post.
  • Microsoft.AspNet.Mvc: This is the core package which adds all the needed components to run Web API and MVC.
  • Microsoft.AspNet.Diagnostics: Basically this package will be used to display a nice welcome page when you request the base URI for the API in a browser. You can ignore this if you want, but it will be nice to display welcoming page instead of the 403 page displayed for older Web API 2.
  • Startup
  • Microsoft.Framework.ConfigurationModel.Json: This package is responsible to load and read the configuration file named “config.json”. We’ll add this file in a later step. This file is responsible to setup the “IConfiguration” object. I recommend to read this nice post about ASP.NET 5 new config files.
Last thing we need to add to the file “project.json” is a section named “commands” as the snippet below:
We’ve added short prefix “ef” for EntityFramework.Commands which will allow us to write EF commands such as initializing and applying DB migrations using KVM.

Step 3: Adding config.json configuration file

Now right click on your project and add new item of type “ASP.NET Configuration File” and name it “config.json”, you can think of this file as a replacement for the legacy Web.config file, for now this file will contain only our connection string to our SQL DB, I’m using SQL Express here and you can change this to your preferred SQL server.
Note: This is a JSON file that’s why we are using escape characters in the connection string.

Step 4: Configuring the ASP.NET 5 pipeline for our Web API

This is the class which is responsible for adding the components needed in our pipeline, currently with the ASP.NET 5 empty template, the class is empty and our web project literally does nothing, I’ll add all the code in our Startup class at once then describe what each line of code is responsible for, so open file Startup.cs and paste the code below:
What we’ve implemented in this class is the following:
  • The constructor for this class is responsible to read the settings in the configuration file “config.json” that we’ve defined earlier, currently we have only the connection string. So the static object “Configuration” contains this setting which we’ll use in the coming step.
  • The method “ConfigureServices” accepts parameter of type “IServiceCollection”, this method is called automatically when starting up the project, as well this is the core method responsible to register components in our pipeline, so the components we’ve registered are:
    • We’ve added “EntityFramework” using SQL Server as our data provider for the database context named “RegistrationDBContext”. We’ll add this DB context in next steps.
    • Added the MVC component to our pipeline so we can use MVC and Web API.
    • Lastly and one of the nice out of the box features which has been added to ASP.NET 5 is Dependency Injection without using any external IoC containers, notice how we are creating single instance scoped instance of our “IRegistrationRepo” by calling  services.AddScoped<IRegistrationRepo, RegistrationRepo>();. This instance will be available for the entire lifetime of our application life time of the request, we’ll implement the classes “IRegistrationRepo” and “RegistrationRepo” in next steps of this post. There is a nice post about ASP.NET 5 dependency injection can be read here. (Update by Nick Nelson to use Scoped injection instead of using Singleton instance because DbContext is not thread safe).
  • Lastly the method “Configure” accepts parameter of type “IApplicationBuilder”, this method configures the pipeline to use MVC and show the welcome page. Do not ask me why we have to call “AddMvc” and “UseMvc” and what is the difference between both :) I would like to hear an answer if someone knows the difference or maybe this will be changed in the coming release of ASP.NET 5. (Update: Explanation of this pattern in the comments section).

Step 5: Adding Models, Database Context, and Repository

Now we’ll add a file named “Course” which contains two classes: “Course” and “CourseStatusModel”, those classes will represents our domain data model, so for better code organizing add new folder named “Models” then add the new file containing the the code below:
Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “RegistrationDbContext” then paste the code snippet below:
Basically what we’ve implemented here is adding our Courses data model as DbSet so it will represent a database table once we run the migrations, note that there is a new method named “OnConfiguration” where we can override it so we’ll be able to specify the data provider which needs to work with our DB context.
In our case we’ll use SQL Server, the constructor for “UseSqlServer” extension method accepts a parameter of type connection string, so we’ll read it from our “config.json” file by specifying the key “Data:DefaultConnection:ConnectionString” for the “Configuration” object we’ve created earlier in Startup class.
Note: This is not the optimal way to set the connection string, there are MVC6 examples out there using this way, but for a reason it is not working with me, so I followed my way.
Lastly we need to add the interface “IRegistrationRepo” and the implementation for this interface “RegistrationRepo”, so add two new files under “Models” folder named “IRegistrationRepo” and “RegistrationRepo” and paste the two code snippets below:
The implementation here is fairly simple, what worth noting here is how we’ve passed “RegistrationDbContext” as parameter for our “RegistrationRepo” constructor so we’ve implemented Constructor Injection, this will not work if we didn’t configure this earlier in our “Startup” class.

Step 6: Installing KVM (K Version Manager)

After we’ve added our Database context and our domain data models, we can use migrations to create the database, with previous version of ASP.NET we’ve used NuGet package manager for these type of tasks, but with ASP.NET 5 we can use command prompt using various K* commands.
What is KVM (K Version Manager)?  KVM is a Powershell script used to get the runtime and manage multiple versions of it being on the machine at the same time, you can read more about it here.
Now to install KVM for the first time you have to do the following steps:
1. Open a command prompt with Run as administrator.
2. Run the following command:
3. The script installs KVM for the current user.
4. Exit the command prompt window and start another as an administrator (you need to start a new command prompt to get the updated path environment).
5. Upgrade KVM with the following command:
We are ready now to run EF migrations as the step below:

Step 7: Initializing and applying migrations for our database

Now our command prompt is ready to understand K commands and Entity Framework commands, first step to do is to change the directory to the project directory. The project directory contains the “project.json” file as the image below:
EF7 Migrations
So in the command prompt we need to run the 2 following commands:
Basically the first command will add migration file with the name format (<date>_<migration name>) so we’ll end up having file named “201411172303154_initial.cs” under folder named “Migrations” in our project. This auto generated file contains the code needed to to add our Courses table to our database, the newly generated files will show up under your project as the image below:
EF7 Migrations 2
The second command will apply those migrations and create the database for us based on the connection string we’ve specified earlier in file “config.json”.
Note: the “ef” command comes from the settings that we’ve specified earlier in file “project.json” under section “commands”.

Step 8: Adding GET methods for Courses Controller

The controller is a class which is responsible to handle HTTP requests, with ASP.NET 5 our Web API controller will inherit from “Controller” class not anymore from “ApiController”, so add new folder named “Controllers” then add new controller named “CoursesController” and paste the code below:
What we’ve implemented in the controller class is the following:
  • The controller is attribute with Route attribute as the following [Route("api/[controller]")] so any HTTP requests that match the template are routed to the controller. The “[controller]” part in the template URL means to substitute the controller class name, minus the “Controller” suffix. In our case and for “CoursesController” class, the route template is “api/courses”.
  • We’ve defined two HTTP GET methods, the first one “GetAllCourses” is attributed with “[HttpGet]” and it returns a .NET object which is serialized in the body of the response using the default JSON format.
  • The second HTTP GET method “GetCourseById” is attributed with “[HttpGet]“. For this method we’ve specified a constraint on the parameter “courseId”, the parameter should be of integer data type. As well we’ve specified a name for this method “GetCourseById” which we’ll use in the next step. Last thing this method returns object of type IActionResult which gives us flexibility to return different actions results based on our logic, in our case we will return HttpNotFound if the course does not exist or we can return serialized JSON object of the course when the course is found.
  • Lastly notice how we are passing the “IRegistrationRepo” as a constructor for our CoursesController, by doing this we are implementing Constructor Injection.

Step 9: Adding POST and DELETE methods for Courses Controller

Now we want to implement another two HTTP methods which allow us to add new Course or delete existing one, so open file “CoursesController” and paste the code below:
What we’ve implemented here is the following:
  • For method “AddCourse”:
    • Add new HTTP POST method which is responsible to create new Course, this method accepts Course object which is coming from the request body then Web API framework will deserialize this to CLR Course object.
    • If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code and an object containing description of the validation error. Thanks for Yishai Galatzer for spotting this out because I was originally returning response of type “text/plain” always regarding the “Accept” header value set by the client. The point below contains the fix.
    • If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code, and in the response body we’ll return an instance of a POCO class(CourseStatusModel) containing fictional Id and description of the validation error.
    • If the course created successfully then we’ll build a location URI which points to our new created course i.e. (/api/courses/4) and set this URI in the “Location” header for the response.
    • Lastly we are returning the created course object in the response body.
  • For method “DeleteCourse”:
    • Add new HTTP DELETE method which is responsible for deleting existing course, this method accepts integer courseId.
    • If the course has been deleted successfully we’ll return HTTP status 204 (No content)
    • If the passed courseId doesn’t exists we will return HTTP status 404.
Note: I believe that the IhttpActionResult response which got introduced in Web API 2 is way better than IActionResult, please drop me a comment if someone knows how to use IhttpActionResult with MVC6.

The source code for this tutorial is available on GitHub.

That’s all for now folks! I’m still learning the new features in ASP.NET 5, please drop me a comment if you have better way implementing this tutorial or you spotted something that could be done in a better way.

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...