Building Your First API with ASP.NET Core – Part II

Creating the API and Returning Resources

Welcome to the creating an API and returning resources module by building your fist API using ASP.NET Core. Part one of this article we crate the project and now time to start our API.

In part one we learnt that we can build various type of middleware’s. One of these is ASP.NET Core MVC Middleware which we need to build our API. Once we got that up and running will learn how to return data from our API and how to interact with our API by sending Http request. Also we are going to discuss how to configure the response, send back to the API consumer.

Middleware for Building an API

What do we need to start building an API? We know from the previous article that we going to have to add some middleware to the http request pipeline in the configure method and that will have to add the framework services to the container in the configure services method.

If we look at previous version those of who work with that will know to build Http serves we used ASP.NET Web API and to build client facing applications we used ASP.NET MVC. This has changed. In ASP.NET Core there is no separate web API framework anymore. Both web API and MVC functionalities now unified in one framework. We called it as ASP.NET Core MVC. Its positions as a reach framework for building web apps and APIs using the model view controller design pattern.

dig2

This makes sense. After all MVC is the design pattern that was used both ASP.NET MVC and ASP.NET Web API. To middleware will have to configure and add to the pipeline is just the ASP.NET Core MVC middleware.

Adding the ASP.NET Core MVC Middleware

The first thing we have to do is add the reference to MVC as the services and middleware are defined in an external dependency. We can do this using NuGet package manager. Package we need is is Microsoft.AspNetCore.Mvc.

nuget.png

Now I am going to add the MVC framework services we need to call AddMvc extension method in to ConfigureServices method. On to the configure method we will have to add the MVC middleware to the request pipeline. To do that we call app.UseMvc.

addmvc.png

Returning Resources

We are building city information API. So cities controller is a good controller to start. To add a controller we can use built in template. Let’s not do that to better understand what is going on.

Let’s add a folder to our controllers and add a class with a name CitiesController. We want to inherit this class from controller class (Namespace: Microsoft.AspNetCore.Mvc). Then we need action that return data. For the moment will keep this very simple. We want to return json as a representation format of our data. For that we can use JsonResult class, this will return json format of the data whatever we pass to the constructor of the class. Still we didn’t have any data what I will do is create some mock data to pass when someone call this API.

controllerget1.png

When consuming Http services like our API to get data back we should sent an Http request with Http method get to Uri that routs to this method. Let start request its self. Any type of client that consume API sent an Http request to that API. You can use browser for that but there are limitations when you want to sending request to create or update resources.

So will use postman to create the request and get the response. We can select the Http method to use for request and Uri and later on we can work with headers and request body but for now we only use Http method and Uri.

getrqst.png

Now run the application and click on the Send button. Once request sent you can see 404 not found status.

getrsp.png

This is because of MVC framework doesn’t know how to map this Uri (http://localhost:52916/api/cities) to the action on the controller that we created. It’s a principle called routing that handle this.

Learning About Routing

Routing matches request URI to controller method. So once we send the Http request the MVC framework passes the Uri and try to map it to one of our controller deriving controllers and corresponding methods on that controller. We can do this two ways.

Convention-based routing

Conventions need to be configured. These type of convention based mappings are typically used when you are using MVC framework to build web application with HTML returning views. For APIs ASP.NET Core team not recommended this approach.

Convention-based routing.png

Attribute-based routing

Allow us to use attribute at controller and action level. For this we use variety of attributes depending on the HTTP method you want to match.

attrib.png

We know we want to respond to a get request. So let’s use HttpGet attribute. We want CitiesController action to be executed when we sent a request to api/cities. So that what we passing as routing template.

getAttribadd.png

Now build the application and run. Then use the postman to send the request. This time we get the result.

result.png

Improving the Architecture with Model Classes

So now we are going to improve our code by adding model classes. Let’s add a Model folder and CityDto.

dto.png

Now What I am going to do is add one more action to the controller where return single city. To do this I need to add one more class to keep data in memory until we properly implement a backend in later article. I am adding another class called CityDataStore with collection of CityDto objects.

storeclass.png

Back to our controller, we can now change our existing code to use the CitiesDataStore and get the data.

Also will implement an action to return a single city. Let’s add a new action GetCity and decorated it with HttpGet attribute. For the Uri of this action is api/cities/{id}. To work with parameters in routing

getcity.png

Using postman you can test this. Result looks like below.

getcitypm

Returning Correct Status Codes

In this section will learn how to return correct status code with our response. In our CitiesController we need to return response with specific status code. Currently we still returning JsonResult. Let’s have a look at JsonResult. If you look at the definition, we see that JsonResult an action result which formats the given object as JSON.

jsresult

But this JsonResult is not what we always want to return. First of all APIs don’t necessarily   work with Json. They should return what consumer asked in the accept header of the request if that format supported but more importantly it’s not always simply a bunch of Json you want to return. We need to be able to return response with specific status code. ASP.NET Core contains set of built in helper method on the controller that all create IActionResult.

Let’s change JsonResult to IActionResult. First try and get city with pass in id. If that doesn’t exist we return 404 not found by using the Not Found method. Otherwise we want to return 200 OK containing the city in the response body.

iactionResult.png

Using postman you can send a request with non-existing city id then you can see 404 status code. Let’s try to get a city that doesn’t exist directly from browser. We know this return 404 not found but we have to open developer tool to see this. There is an alternative we can used. Status code pages.

Let’s open configure method of the Startup class again. ASP.NET Core contains Status code pages middleware, if we add that to the request pipeline a simple text based handler for common status codes added.

statuspages.png

Now test using browser you can see the page include the message.

browserTest.png

Returning Child Resources

In this section will combine what we learnt until now to return point of interest of a city including correct status code.

First add a class PointOfInterestDto. Then extend the CityDto class to include point of interest collection. Also add some data that you like to CitiesDataStore.

addpointinterest.png

Now will add a new controller called PointOfInterestController with two action methods. One to get all the point of interest list for a city and other to get the one point of interest.

pointcontroller.png

Now we can test this like below.

resukt1resukt2

 

This is the complete of the part two of the Building Your First API with ASP.NET Core series of article.

Code Sample: Part Two Code Sample

Next article: Building Your First API with ASP.NET Core Part III – Manipulating Resources (Coming Soon)

 

Advertisements

Building Your First API with ASP.NET Core – Part I

Getting Familiar with ASP.NET Core

Introduction to ASP.NET Core

ASP.NET Core is a new open-source and cross-platform framework for building modern cloud-based Internet-connected applications, such as web apps, IoT apps and mobile backends. It was architected to provide an optimized development framework for apps that are deployed to the cloud or run on-premises. It consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions. You can develop and run ASP.NET Core apps on Windows, Mac and Linux. ASP.NET Core apps can run on .NET Core or on the .NET Framework.

Create ASP.NET Core project

To start the development of our application. I am going to create a new ASP.NET Core application using visual studio 2015.

Steps: File -> New ->Project

Select the ASP.NET Core and then select empty type. Reason why I selected empty type I just want to use the minimum codes that required to start the project and that is the best way to understand what is going on.

cp1cp2

Before we jump in to the development will go through the project structure and specific classes added to the project when we create this.

cp3

Once you create the project you can see its added a ASP.NET Core project which is includes Program.cs and Startup.cs. Let’s go and explore those classes.

Program.cs

Program is our starting point of the application. Most of you familier with this because you use aconsole applications before. Asp.Net core project also a console application. More specifically its call ASP.Net specific libraries.  In our case, will be running a web application so we need to host this application. Because of that WebHostBuilder instance is initialized.

program

SO, we are hosting a web application we need a web server.Asp.NET Core completely decoupled from the environment that host the web application. It’s ships with two different http servers.Web listener which is windows only server and Kestrel cross flat form web server. Kestrel is the default but we  are  using visual studio here so it will use IIS express as web server.

Startup.cs

Startup class is the entry point of an application. At this moment its included two methods, ConfigureServices and Configure.Configuration services used to add services to container and configured those services. This container used for dependency injection. We will talk about dependency injection later in this article series. But what are services in ASP.NET Core world. Service is a component that is intended for common consumption in an application. Those services can be built in services or custom service that we are creating during our application development.

startup

The ASP.NET Core Request Pipeline and Middleware

Whenever HTTP request comes in something must handle that request so eventually it’s a result of HTTP response. Those pieces of codes that handle the request and resolved in responses that make up the request pipeline. What we can do is configure that pipeline by adding middleware which are software components that are assembled in to an application pipeline to handle requests and responses. If you worked with older version of ASP.NET you know that module and handlers to care of this for us. In ASP.NET Core those are taken over by middleware. Few samples that we can add to this pipeline are diagnostic middleware or middleware to handle authentication. Even MVC is a piece of middleware that can be added to request pipeline.

pipeline

Now will look at such a request. The Asp.Net request pipeline consist of a sequence of request delegates called one after the next from one piece of middleware to the next. Each of those can perform operations before and after the next delegates. Important to know that each component choices whether to pass the request to next component in the pipeline or not. So, the order in which we added the middleware to the request pipeline matters. Good example is authentication middleware, if authentication not success request should not pass to the next middleware and immediate response unauthorized request.

Configuring the ASP.NET Request Pipeline

In this section I am going to show you how to configure the ASP.NET Core request pipeline. I am going to show you when we are in the development environment I want to show the developer friendly Error message when exception thrown. To do this actually we no need to do anything its already built in.

Let’s have a look at this statement app.UseDeveloperExceptionPage();

pc

This configures the request pipeline by adding a developer exception page middleware to the request pipeline. So now when exception thrown this piece of middleware will handle it.

To test this, I will do a small change to my code to throw and exception.

ex

If you run the application you can see a nice error page lot of useful information’s.

Now check the code belove carefully and you can identify there is a specific condition check before use the developer friendly error page. That condition used to make sure this developer friendly error only show when application running in development environment.

ex2.png

May be this is a good time to talk about separate environments. Because we might need to execute different piece of code depending on environment and this is a good example of that. The developer exception page that is not something we want to show everyone. We need this during development but not in production.

Let’s have a look debug tab of the project properties.

debug.png

Here we can find ASPNETCORE_ENVIRONMENT variable its set to development. ASP.NET Core references environment variable hosting environment, to describe the application currently running. Three values are used Development, staging and production.

Now will change our code to handle the error differently when application running in production. What I want is catch the exception and log it. There is a middleware for that as well, the exception handler middleware.

addex.png

Go to the debug tab and change the ASPNETCORE_ENVIRONMENT to production and run the application you will get the blank page. If you still get the developer error page you need to restart the IIS express.

This is the complete of the part one of the Building Your First API with ASP.NET Core series of article. This covered all the basic information that you should know about the ASP.NET Core.

Code Sample: Part One Code Sample

Next article: Building Your First API with ASP.NET Core Part II – Creating the API and Returning Resources

 

Building an Owin Authentication Middleware

Recently I worked on a project which is used Oauth as authentication mechanism. In this project we need to implement a custom authentication mechanism as well to validate some users. While I am researching on this I found Owin and Katana offers a flexible pipeline for external authentication with existing providers for authentication by Google, Facebook, Twitter and more. Good news for me it is also possible to write your own custom authentication provider and get full integration with the Owin external authentication pipeline and ASP.NET Identity.

In this article I am going to explain how we can develop your own custom authentication provider and get full integration with the Owin external authentication pipeline and ASP.NET Identity.

Normally Katana middleware is made up of 4 classes.

  • The main MyCustomAuthenticationMiddleware class.
  • The internal MyCustomAuthenticationHandler class doing the actual work.
  • A MyCustomAuthenticationOptions class for handling settings.
  • An extension method in MyCustomAuthenticationExtensions for easy setup of the middleware by the client application.

 

MyCustomAuthenticationOptions class

Any middleware will need some kind of configurations. It is stored in an options class. To work with the Katana base classes, it must inherit AuthenticationOptions class in Microsoft.Owin.Security namespace, which contains some mandatory options that are used by the framework. In my class I am going to use authentication type option only.

options

MyCustomAuthenticationHandler class (Inside MyCustomAuthConfig.cs)

This is where a real handler would inspect the incoming authentication ticket from the external authentication server. My Custom middleware just creates an identity with the values from the configuration (See custom middleware below).

handler

MyCustomAuthenticationMiddleware class

The middleware is a factory that creates instances of the handler that does the actual work of processing requests. Only one instance of the middleware is instantiated. The middleware constructor checks the configuration in the options class and if certain properties are null, it adds some defaults that are dependent on the previous middlewares in the pipeline.

middleware

MyCustomAuthenticationExtensions

The IAppBuilder.Use method takes an object as the first parameter, which has the advantage that a middleware won’t need to have a reference to a particular assembly containing a specific middleware interface. But using an untyped object makes it more confusing for callers. This is where the extension method comes into the play, it makes it easy to register the middleware in the Owin pipeline.

extention

Finally my MyCustomAuthConfig look like this.

config

In your startup class you need to call the  MyCustomAuthConfig.SetupVerification(app) method to apply your implementation.

 

Ref:

http://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.Security.Google/GoogleAuthenticationHandler.cs

Better way to handle Ajax call in your AngularJs code

If you are working on web applications especially, we have to use JavaScript to handle our front end code in most projects. In this article I am going to discuss a better way of handling Ajax calls within my project.

I have created a new MVC 4 project using visual studio 2012. In this project I have written couple of methods in an angular service, to access MVC controller methods in order to get and save data. Those methods are shown below.

service with ajax calls

The above service can access any angular controller to consume the data from the back end. In my code the user angular controller works with this service.

controller code

Now within our project we can write many number of Ajax calls like in the above sample. There will be no problems if you do it correctly, your application will work nicely. But just think if you want to change settings of your Ajax calls, you will have to do it may places. Not only that but if at a later point if you decide to change all these Ajax calls to angular $resource or some other technique, that will be a lot of work for you isn’t it?

So how can we control this and make your code more maintainable? I am going to use angular service to do this. I added a new service that manages all Ajax calls. All my other angular services or controllers use that service to do any Ajax calls that requires to access the data.

ajaxservice

The code below shows how we can use this common service within other services and controllers.

new user service

Now you can understand that my change brings more control on these Ajax calls because changing one place will affect all the Ajax calls. Or if you want to do it only for one of your Ajax calls you can do it as well.

To prove the above two points I will do the following changes to my code.

Make all Ajax get calls dataType property be equal to ‘json’. Changing one place will affect all the Ajax get calls.

ajaxserviceChange data type

My second change is changing the cache property to be equal to ‘false’ when I call the user service user details get call.

new user service changes

Hope this article will help you to improve your JavaScript code. Also you can get sampe code form here

JavaScript Constructor Pattern

In Object Oriented programming languages a constructor is a special method used to initialize a new object once memory has been allocated for it. When we take JavaScript almost everything is an object.

Object constructors are used to create specific types of objects. Constructor preparing the object for use and accepting parameters a constructor can use to set the values to properties and methods when object is first created.

Object Creation
Two common ways used in JavaScript to create objects. Those methods are as follows:

//Create a new empty object
var myCar = {}


//Which is a shorthand for the object constructor
var myNewCar = new Object();

Basic Constructor
As we know JavaScript doesn’t support the concept of class, but importantly it does support constructor functions that work with objects. For a call to a constructor function with the keyword new, we can tell JavaScript would like the function to behave like a constructor and instantiate a new object with members in the function.

Inside our constructor, the keyword this references the new object that’s being created. So now we are going to create a basic constructor like follow:

function Car(model, year, mileage, color) {
     this.model = model;
     this.year = year;
     this.mileage = mileage;
     this.color = color;

     this.toString = function () {
         return this.model + "has done " + this.mileage + ' miles'
     }
}

//Usage
var civic = new Car("Honda Civic", 2012, 5000, "Black");


//browser console will show the output
console.log(civic.toString());

This sample code shows us the simple version of the constructor pattern. Still this implementation has few problems. Those are

  • It makes inheritance difficult.
  • Function such as toString() are redefined for each of new object created using car constructor.

So That means this is not optimal, as the function toString() should be ideally be shared between all instances of the car type. Next section will see how we can overcome these issues.

Constructors with Prototype
JavaScript functions have a property called a prototype. When we call a JavaScript constructor to create new object, all the properties of the constructor’s prototype are available to the new object. In this way, multiple car objects can be created that access the same prototype. Now will extend our example as follows:

function Car(model, year, mileage, color) {
    this.model = model;
    this.year = year;
    this.mileage = mileage;
    this.color = color;

}

Car.prototype.toString = function () {
    return this.model + "has done " + this.mileage + ' miles'
}

//Usage
var civic = new Car("Honda Civic", 2012, 5000, "Black");


//browser console will show the output
console.log(civic.toString());

After new prototype implementation, the single instance of toString() will now be shared between all car objects.

In this article we learn constructor pattern and used prototype property to make it optimal. Hope this will help you to understand this pattern.

Developer Tips – Part Two

When we work on our project we always press F5 or use the build menu to build the application to make sure our code is compiling. After we see the build successful message most of us think our code is correct. Sometimes even though the code is working there can be mistakes or bad coding practices used within the code. So how can we find them? Warnings section in error list will show these.

image1

In this article I am going to discuss about warnings in visual studio. Most of the developers forget or do not care about this section. Remember that this a really useful and important section just as the errors. You might ask why the warnings are of any importance if your code can execute. The reasons are

  • Warnings show most of the mistakes in your coding
  • Fixing the warnings will improve the performance of the application
  • It will help to develop maintainable code of good quality

As a start check about the settings for warnings in visual studio. In the solution explorer select a project and right click and select property. Then you will see the Build tab. using the build tab we can do the following

  • Set warning level

The minimum warning level you can set for the build chose from this option. Valid values are 0-4.

0 – Turns off emission of all warning messages.

1 – Displays severe warning messages.

2 – Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.

3 – Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.

4 – Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line.

  • Treat warnings as errors

This option is important if a developer wants to fix the warnings before he commits the code. If you enable this option it will force you to fix the warnings.

image2

Now I am going to discuss a couple of warnings to give you an idea of how important these can be.

  • Variable declared but never used

image3

Now you can see that I created a variable called total and never used it. What is the effect of this mistake? Every time when we call this method it will create a variable and when we exit, the method run time will delete it. This is an unwanted step to run-time. If we make the same mistake many times our application can have some performance issues. By avoiding these type of mistakes we can improve our application quality.

  • Possible mistaken empty statement

image4

When you see the code you can identify that this is a mistake. If we do not consider warnings this will not get identified until we run and test this code. If we consider warnings we can identify our mistakes upfront and reduce the bugs within our code.

I took two simple examples to give you an idea about warnings and how important they are to developers. If you want more details about warning you can refer following MSDN link:

http://msdn.microsoft.com/en-us/library/ms228296(v=vs.90).aspx

After reading this article I hope you all think seriously about warnings. Happy coding.