ASP.NET Core

ASP.NET Core Basics: API Controller

This week’s post is going to cover the creation of an API controller. The starting point for this post is based on this post from last week and the starting state of the code can be found here.

Scaffolding

Using the same Contact model class from last week’s post Entity Framework Core’s scaffolding can be used to generate an API controller for us with all the read and write actions already written. To begin in the Solution Explorer window right click on the Controllers folder and select Add > New Scaffolded Item.

AddNewScaffoldedItemMenu

On the Add Scaffold dialog select API Controller with actions, using Entity Framework. This option will create an API controller with read and write actions based on a model.

AddScaffoldApi

On the Add Controller dialog for the model class select the Contact class, for the data context class select the existing ContactsContext. Finally enter the controller name you would like to use. I am using ContactsApiController since the MVC controller from last week’s post is already named ContactsController.

AddApiControllerDialog

Click add and the scaffolding process will create a ContactsApiController in the Controllers folder. With that the project now contains a fully functional contacts API that will handle gets, puts, posts and deletes with zero code changes.

Test with Postman

Postman is a great tool that I always use when developing an API that allows me to exercise all the functions of the API before any clients have been built. I know you can do some of the same things using a browser, but Postman was built for this type of usage and it shows. Postman is free and you can grab it from here as a Chrome app or they have app versions available here.

After installing the application and running it you will see something like the following.

PostmanBlank

It is best to have some data available for testing so in the case of this application I recommend using the UI added in last weeks post to add a couple of contacts.

Now that some data is available it is time to test the GetContact function on the ContactsApiController. If you run the application it should open in a browser from which you can copy the URL, or right click on the project select properties then on the Debug tab copy the URL from the App URL field.

ProjectProperties

Paste the base URL in the URL box in Postman and then add on the route for the endpoint you are wanting to test. In this case I want to test the the GetContact function on the ContactsApiController so I will be using the a URL of http://localhost:13322/api/contactsapi. Next make sure contact application is running and then click the send button in Postman. The application should respond and the results of the API call will be displayed on the body tab of Postman.

PostmanGetContacts

Postman can be used to try out pretty much all aspects of the API that an application has. For example if you wanted to test out the PostContact then in Postman click the down arrow next to Get and select Post. Next select the upper body tab (in the request area) and the click the raw radio button. Then to the right of the radio buttons hit the down arrow and select JSON (application/json) and then it the large text box you can enter the JSON that will be sent to the server when you click the send button. The following is an example of a post request.

PostmanPostContact

Wrapping Up

This application now has a fully functional API and we have covered how test it using Postman.

The next step would be to create some sort of client to actually utilized the API such as an Aurelia or Angular 2 application.

The code for this post can be found here.

ASP.NET Core Basics: API Controller Read More »

ASP.NET Core Basics: MVC Controller with Entity Framework Core

Last week’s post covered the installation and creation of a new project in ASP.NET Core. This week I will be expanding that existing project to create a basic contact list which will use Entity Framework Core and its scaffolding capabilities to generate the needed files from a model class. This code from last week is being used as a starting point for this post.

Add a Model

To start off I need a class to represent the information for a single contact. In the default setup the proper place to store this type of class is in the Models folder. To add a new class from the Solution Explorer window right click on the Models folder and select Add > Class menu option.

AddClassMenu

This menu choice will bring up the Add New Item dialog defaulted to adding a new class. Enter the name as Contact.cs and click Add.

AddNewItemDialogContact

The following is my resulting Contact after adding the properties of a contact that this application is going to use.

namespace Contacts.Models
{
    public class Contact
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string PostalCode { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
    }
}

Scaffolding

Now that the application knows what a Contact looks like we can take advantage of a feature of Entity Framework Core called scaffolding. Scaffolding can be sued to create a number of different setups based on a model, but in this case it I am using it to generate a MVC Controller with views, using Entity Framework which will result in a controller, DbContext and associated MVC razor views being created.

In the Solution Explorer window right click on the Controllers folder and select Add > New Scaffolded Item.

AddNewScaffoldedItemMenu

On the Add Scaffold dialog select MVC Controller with views, using Entity Framework. This is the only option that will create views. Now click the Add button.

AddScaffoldDialog

The Add Controller dialog will be shown next. First select the model that should be the base of the scaffolding operation which is the Contact class for this project. For the data context class option I used the plus (+) button to add a new one since this project doesn’t have an existing data context that I want to use.

AddControllerDialog

After clicking add and letting the process finish the Controllers folder will now contain a ContactsController and in the Models folder there will be ContactsContext. I always move the newly created context out of the Models folder and into the Data folder to match the location used for the ApplicationDbContext.

Entity Framework Migration

Now that the application has a contact model and DbContext it is time to create an entity framework migration which is the mechanism entity framework uses to create and/or migrate a database to match the changes made in the models of an application. Migrations can be added within Visual Studio via the Package Manager Console or from a command prompt using the .NET CLI. I am going to walk through both, but keep in mind you only need to use one.

Package Manager Console

To open the Package Manager Console use the View > Other Windows > Package Manager Console menu. Which show a window that looks like the following.

PackageManagerConsole

To add a migration use run the Add-Migration Init-Contacts -Context ContactsContext command. The Package Manager Console is using powershell so Add-Migration is a command that take a parameter that is the name of the migration which is Init-Contacts in this case. -Context ContactsContext is required in this application because it contains more than one DbContext and the command has to know which DbContext it is working with.

.NET CLI

Open a command prompt and navigate to your project’s directory and then run the dotnet ef migrations add Init-Contacts –context ContactsContext command. This is does exactly the same thing as the Package Manager Console above with just slightly different syntax.

Regardless of which version is used you will see a new Migrations folder added to the root of the project that contains a snapshot of the models referenced by the relevant DbContext as well as a migration file named by using a time stamp plus the migration name.

Automatic Database Migration

In the early stages of a project (or always if it meets your need) it is nice to automatically apply migrations instead of having to do so manually using the package manager console or the .NET CLI. One way to accomplish this is to add a static flag to the constructor of the DbContext in question and if that flag is false then use Database.Migrate() to apply any migrations that the database is missing. Here is an example using my ContatsContext class with the flag named _created.

public sealed class ContactsContext : DbContext
{
    private static bool _created;
    public DbSet<Contact> Contact { get; set; }
    public ContactsContext(DbContextOptions<ContactsContext> options)
        : base(options)
    {
        if (_created) return;
        Database.Migrate();
        _created = true;
    }
}

Add Navigation

At this point you could type in a URL that would take you to the index action of the new ContactsController, but it would be much more useful to add a link to the sites navigation bar to provide an easy way to access the new functionality. The code for the navigation bar can be found in _Layout.cshtml which is located in the Views > Shared folder.

The navigation bar is defined using an unordered list with a class of “nav navbar-nav”. Add a new link to the unorderd list labeled Contact List. This new link needs to point to the index action of ContactsController. ASP.NET Core provides some tag helpers to assist in building links to controller actions. Using the asp-controller and specify “Contacts” as the controller which will resolve to the ContactsController and then use asp-action set to “Index” to point to the index action.

<ul class="nav navbar-nav">
    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
    <li><a asp-area="" asp-controller="Contacts" asp-action="Index">Contact List</a></li>
    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
</ul>

Wrapping Up

Now when the application is run there will be a link for Contact List at the top that will trigger actions in the new controller and backing database table.

Next week I play to take this same project and add a web API end point to it and show how that end point can be verified using Postman.

The code that goes with the post can be found here.

ASP.NET Core Basics: MVC Controller with Entity Framework Core Read More »

ASP.NET Core Basics: Project Creation

With ASP.NET Core released it seems like a good time to do a series of posts on the basics of this new platform starting with getting a new project up and running.  In this post I am going to walk through installation of ASP.NET Core and then move to project creation. This project will end up being a basic contact list application although there will not be much specific to that end goal in this post.

Installation

All the software needed for this post can be found at http://dot.net. I will be using Visual Studio 2015 in my examples and if you don’t have it installed already it can be downloaded using the Download Visual Studio 2015 button on the right of the above page or by clicking here. If you already have Visual Studio 2015 installed please ensure you have installed Update 3.

The next bit of software you will need is found by clicking the Download .NET Core 1.0 or clicking here. This page has a good write up getting started with .NET Core, but all you need is the install for .NET Core 1.0 for Visual Studio which can be found here.

To verify that .NET Core is installed open a command prompt and run dotnet –version which will print the current version of .NET Core you have installed. As of this writing this my version is 1.0.0-preview2-003121. While .NET Core its self has been officially released the tooling is still in preview which is why the version contains preview2-003121.

Project Creation

Launch Visual Studio and from the File > New menu select Project…

NewProject

This will load the New Project dialog. On the left side under Templates > Visual C# > .NET Core select ASP.NET Core Web Application (.Net Core) or you can use the search box in the upper right of the screen to search for “ASP.NET Core Web Application (.Net Core)”.

NewProjectDialogContacts

Next on the New ASP.NET Core Web Application dialog select Web Application. This option creates an application with example MVC Views (razor) and an example controller. Notice the note that this template can be used for RESTful HTTP services as well. Next click the Change Authentication button.

NewAspNetCoreWebApplication

For this example I am going to use Individual User Accounts. This option adds UI, models, controllers, etc. to allow registration and management of user accounts. Since the option needs a database to store account information it include Entity Framework Core. Click OK on the Change Authentication dialog and then click ON new web application dialog.

ChangeAuthentication

Project Overview

After the creation process is finished got to the Solution Explorer window and you will see a set up similar to the following.

SolutionExplorer

I am going to point out a few of the files and folder that are part of a newly created application. Fist is wwwroot which is where static files will be severed as long you are using the static files middleware.  This is where images, CSS and JavaScript should go.

appsettings.json is where you will find connection strings and logging settings by default. Your own settings can be added here as well.

project.json is where you will find all your project’s dependencies (using the NuGet UI or Package Manager console both write to this file), tools, frameworks, build options, runtime options, publish options and scripts are all defined. Thankfully this file has good support for intellisense if you decide to edit it manually. This file covers a lot, but for this introduction I am going to avoid digging into the specifics.

Startup.cs is the last file I want to call out. Its generated contents are fine for this example project, but it has a couple of functions you should be aware of. First ASP.NET Core comes with dependency injection built in and the ConfigureServices function is where items are registered with the built in container. The second function is Configure and this is the function where the HTTP request pipeline for your application is configured using various middleware.

Wrapping Up

At this point you have a web application that can be run (press F5 to run with the debugger attached or Ctrl + F5 to run without the debugger). With no code changes you now have a web application that has basic navigation, controllers, views and authentication.

With this series of post things are being kept intentionally short and focused on one or two main topics. Next week will build on this basic project by adding in the ability to manage contacts, using a new controller and associated razor view which will be persisted to a database using Entity Framework Core.

The code that goes with this post can be found in this GitHub repository.

 

ASP.NET Core Basics: Project Creation Read More »

Enable Scaffolding without Entity Framework in ASP.NET Core

Background

While working on a MVC 6 application backed by a web API application which resides in a separate project I found myself wanting a quick way to use a model as a base to generate a controller and associated CRUD razor views. If a project is using entity framework this is simple to accomplish, but since my project is using web API calls instead of entity framework scaffolding is unavailable. Instead of manually creating all the needed parts I decided to try and enable the scaffolding bits that are available in projects using entity framework.

Getting Started

The first step I took was to look at the project.json from an application using entity framework. This helped me identity the dependencies and tools that might be needed for the scaffolding process. The following are the new items from the dependencies section.

"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
  "version": "1.0.0-preview2-final",
  "type": "build"
},
"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
  "version": "1.0.0-preview2-final",
  "type": "build"
}

And the new items from the tools section (spoiler Microsoft.VisualStudio.Web.CodeGenerators.Mvc isn’t actually needed).

"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
  "version": "1.0.0-preview2-final",
  "imports": [
    "portable-net45+win8"
  ]
},
"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
  "version": "1.0.0-preview2-final",
  "type": "build"
}

Failed dotnet restore

With the above changes dotnet restore fails with this error:

Package Microsoft.Composition 1.0.27 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package Microsoft.Composition 1.0.27 supports: portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259)
One or more packages are incompatible with .NETCoreApp,Version=v1.0.

I double checked that the entity framework project was using the same versions. It was indeed using the same versions, but its restore worked fine.

The fix

This is a known issue which can be found on github here. The issues is caused by Microsoft.VisualStudio.Web.CodeGenerators.Mvc in the tools sections which I finally found out is not actually needed to enable scaffolding. To be clear the only change needed in the tools section the addition of the following and Microsoft.VisualStudio.Web.CodeGenerators.Mvc is not needed.

"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
  "version": "1.0.0-preview2-final",
  "imports": [
    "portable-net45+win8"
  ]
}

Scaffolding

Right click the Controllers folder and select Add > Controllers… (this is the menu enabled by the changes above).

AddController

The above launches the Add Scaffold dialog. Here select “MVC Controller with views, using Entity Framework”. This is the only built in option that creates views. Since this project isn’t using entity framework it will require a little clean up, but it is still faster than creating the views manually.

AddScaffold

After clicking add you will see the following screen. Select the model class to be used during the scaffold. For the data context class click the plus (+) button and enter a name (don’t spend any time on the name the resulting file will be deleted in the next step. Finally enter a controller name and click Add.

AddScaffoldController

Cleaning up the scaffold

In the models folder delete the data context class that was created, TestContext in this case. The removal of the TestContext will cause errors in the TestController which can all be removed (the constructor and private field used to hold the context) and replaced with calls to whatever back end system you happen to be using in your application. Finally in the Startup class remove the last reference to the TestContext.

Wrapping up

That is all the changes that were required other than adding a reference to the test index page to the home page of the application. Not sure this is the most efficient method ever, but for me it is easyer than creating the razor pages myself manually. In the future I may do some digging and determine what is required to create my own scaffolding option.

Enable Scaffolding without Entity Framework in ASP.NET Core Read More »