Thursday, March 26, 2015

Using Web API in ASP.net 5

In my last post I created a Web Project using ASP.net 5. Now we will create some web api controllers.
First, add ASP.net MVC nuget package to the project.
Then change the Startup.cs class like below.
When you run the application, the browser must open following page, which means your IIS works correctly.
In ASP.net 5, there are two primary concepts.

  • Middleware
Middleware is in the HTTP pipeline. When HTTP request comes in it will go through all the middleware according to the order they have defined. After complete that request, response with flows back through the same route.
  • Services
Using dependency injection pattern, services are availabled to all middleware components. For example, DbContext, Logger service and etc.

Change the Startup class like below. Above mentioned middleware and Service codes are applied from Startup class. This code has configured to use DbContext using DI pattern.
Create folder named Controllers and add a Web API Controller class like below.
If you have data in your database, then you will be able to see an output like below.
Assume, there was an exception occurred. Change the web api controller code like below.
Change the Startup.cs file content.
When you run the project, you will see a beautiful error handling page which contains lots of details.

No comments:

Post a Comment