ASP.NET WEB API With Entity Framework - Part 3

Before proceeding to this article, please go through my previous articles:

In this article we are going to learn about routing and the authentication in ASP.NET WEB API, create a new WEB API project with individual authentication as the following figures.

 
 
 

From the above step you will get a project with some sample API controllers, 
Now I’m not going to create any API controller classes, I’m just going to use these predefined API controller to explain about the routing and authentication in ASP.NET WEB API.

  

From the above image you can notice that Account and values controller are predefined controller which came with the template (individual authentication).

Run the project, and navigate to Help page in browser,
 
 

From the above image you can notice the different API’s in Account and Values controller.

Authentication in ASP.NET WEB API  

The Account Controller in the project will give the complete flow of the authentication, 
Let us do a registration using api/Account/Register API in the Account controller, 
  1. [AllowAnonymous]  
  2.         [Route("Register")]  
  3.          public async Task<IHttpActionResult> Register(RegisterBindingModel model)  
  4.              {  
  5.                       if (!ModelState.IsValid)  
  6.             {  
  7.                 return BadRequest(ModelState);  
  8.             }  
  9.   
  10.             var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };  
  11.   
  12.             IdentityResult result = await UserManager.CreateAsync(user, model.Password);  
  13.   
  14.             if (!result.Succeeded)  
  15.             {  
  16.                 return GetErrorResult(result);  
  17.             }  
  18.   
  19.             return Ok();  
  20.         }  
[AllowAnonymous] is the attribute which is decorated for this Register Http action tells that this action can be used by all the users without any authentication.

Response

 
 
The registered record which is stored in table as in the following figure,
 
 
Suppose if we need to access GET api/Account/UserInfo API in the Account controller we need to login as user, I’m not going to use any UI to do login by consuming the API, I’m going to use Postman tool to do these operations.
 
Login as User
 
Open the Startup.Auth.cs file under APP_Start folder, Get the token end point, in my case it is,  

  1. TokenEndpointPath = new PathString("/Token"),  

This End point should be a POST request with,

  • Content-Type: aaplication/x-www-form-urlencoded.
  • Request Body: should consist of username, password, grant-type.
Response in PostMan
  
We got the access token using this token response, now we can access the HTTP action method which is authenticated using this access_token, For example, consider the following HTTP GET action Method with authentication which is in Account controller.
  1. [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]  
  2.        [Route("UserInfo")]  
  3.         
  4.         public UserInfoViewModel GetUserInfo()  
  5.         {  
  6.             ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);  
  7.   
  8.             return new UserInfoViewModel  
  9.             {  
  10.                 Email = User.Identity.GetUserName(),  
  11.                 HasRegistered = externalLogin == null,  
  12.                 LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null  
  13.             };  
  14.         }  


Response of /api/Account/UserInfo

To access this Action we need to pass the header as Authorization: bearer access_token (which we got from the previous POST request)


Routing in ASP.NET WEB API

The Visual Studio project template for Web API creates a default route:

  1. config.Routes.MapHttpRoute
  2.          (  
  3.               name: "DefaultApi",  
  4.               routeTemplate: "api/{controller}/{id}",  
  5.               defaults: new { id = RouteParameter.Optional }  
  6.           );  

You can find it in WebApiConfiq.cs under APP_Start folder. The default route template for Web API is "api/{controller}/{id}", where api-> literal path segment and {controller} and {id}-> placeholder segments. Here are the steps that how the Web API selects the controller and the action:

For example let we take POST: api/Account/Register API URI,

Step 1: 

Firstly, it will find the controller, In our case the controller name is Account, so it will check the Account controller is available or not in the application.

Step 2: 

It will find the action in the controller, Web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name
, in our case our action name is Register with POST request, so the Web API looks whether the Register action is available in the Account controller or not in the application

Step 3: Other placeholder variables in the route template, such as {id}, are mapped to action parameters.

Customizing the Routing:

Instead of using convention naming for HTTP methods, we can explicitly represent the HTTP method for an action by decorating the action method with the HttpGet, HttpPut, HttpPost, or HttpDelete attribute.

Let us take API GET api/GetValues from Values Controller,

  1. public IEnumerable<string> GetValues()  
  2.       {  
  3.           return new string[] { "Hello""Web API" };  
  4.       }  
Respone of GET api/values API

 

We can also customize
the routing in above action method like, 
  1. [HttpGet]  
  2.         public IEnumerable<string> Valuelist()  
  3.         {  
  4.             return new string[] { "Hello""Web API" };  
  5.         }   
Routing by Action Name
 
Web API uses the HTTP method to select the action. However, we can also create a route where the action name is included in the URI just by modifying the routeTemplate as in the following code, 
  1. config.Routes.MapHttpRoute
  2.             (  
  3.                 name: "DefaultApi",  
  4.                 routeTemplate: "api/{controller}/{action}/{id}",  
  5.                 defaults: new { id = RouteParameter.Optional }  
  6.             );  

For example consider the following action method in the Values Controller:

  1. [HttpGet]  
  2.         
  3.         public IEnumerable<string> Valuelist()  
  4.         {  
  5.             return new string[] { "Hello""Web API" };  
  6.         }  
Response of GET api/values/valuelist API
 
 
 
We can override the action name by using Action Name [HttpGet]  
  1.         [ActionName("TestList")]  
  2.         public IEnumerable<string> Valuelist()  
  3.         {  
  4.             return new string[] { "Hello""Web API" };  
  5.         }  


Response of /api/values/TestList API

 
 
Attribute Routing: To enable the attribute routing, call MapHttpAttributeRoutes during configuration, in the WebApiConfiq file, 
  1. public static void Register(HttpConfiguration config)  
  2.         {  
  3.          config.MapHttpAttributeRoutes();  
  4.         }  


Attribute routing can be combined with convention based routing. To define convention-based routes, call the MapHttpRoute method.

  1. public static void Register(HttpConfiguration config)  
  2.        {  
  3.           
  4.   
  5.            // Web API routes  
  6.            config.MapHttpAttributeRoutes();  
  7.   
  8.            config.Routes.MapHttpRoute(  
  9.                name: "DefaultApi",  
  10.                routeTemplate: "api/{controller}/{id}",  
  11.                defaults: new { id = RouteParameter.Optional }  
  12.            );  
  13.        }  
Route Attribute
 
Example of a route defined using an attribute, 
  1. [HttpGet]  
  2.        [Route("api/valuesList/{id:int}")]  
  3.         public string Get(int id)  
  4.         {  
  5.             return "The entered ID is: " + id;  
  6.         }  
 Response of api/valuesList/{id:int}
 
 
 
We can set a common prefix for an entire controller by using the [RoutePrefix] attribute: 
  1. [RoutePrefix("api/ValuesList")]  
  2.     public class ValuesController : ApiController  
  3.     {  
  4.         // GET api/values  
  5.   
  6.         [HttpGet]  
  7.         [Route("")]  
  8.           
  9.         public IEnumerable<string> Valuelist()  
  10.         {  
  11.             return new string[] { "Hello""Web API" };  
  12.         }  
  13.   
  14.         // GET api/values/5  
  15.         [HttpGet]  
  16.        [Route("{id:int}")]  
  17.         public string Get(int id)  
  18.         {  
  19.             return "The entered ID is: " + id;  
  20.         }  
  21. }  
Response of the above action methods:
 
 
 
   
 
We can override the route prefix by using tilde(~)
  1. [HttpGet]  
  2.        [Route("~/api/ OverrideList/{id:int}")]  
  3.         public string Get(int id)  
  4.         {  
  5.             return "The entered ID is: " + id;  
  6.         }  
 Response of /api/OverrideList/{id:int}

 
 
Route Constraints: Route constraints will restrict how the parameters in the route template are matched. The general syntax is "{parameter:constraint}", 
  1. [HttpGet]  
  2.         [Route("{name}")]  
  3.           
  4.          public string GetName(string name)  
  5.         {  
  6.             return "The entered string is: " + name;  
  7.         }  
Response of api/ValuesList/Hello
 
 
  1. [HttpGet]  
  2.        [Route("{date:DateTime}")]  
  3.   
  4.        public string GetDate(DateTime date)  
  5.        {  
  6.            return "The entered date is: " + date;  
  7.        }  
Response of api/ValuesList/12-23-1991
 
 
 
Non-Actions

The NonAction attribute is used to prevent a method from getting invoked as an action. This attribute tells to the framework that the method is not an action, inspite of that it will match with routing rules or not,
  1. [HttpGet]  
  2.         [Route("{name}")]  
  3.         [NonAction]  
  4.          public string GetName(string name)  
  5.         {  
  6.             return "The entered string is: " + name;  
  7.         }  

 
Response of api/ValuesList/Hello

 
Conclusion:

From this article we have learned about routing and some basics about authentication in ASP.NET WEB API. There are more things need to be discussed regarding the authentication and authorization in ASP.NET WEB API, So in PART-4 let me share some in-depth concept of authentication and authorization in ASP.NET WEB API. 

I hope you enjoyed this article. Your valuable feedback, question, or comments about this article are always welcomed.

Up Next
    Ebook Download
    View all
    Learn
    View all