Before proceeding to this article, please go through my previous articles:
- ASP.NET WEB API with Entity Framework 6 code first technique- Part I
- ASP.NET WEB API with Entity Framework 6 code first technique- Part 2
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,
- [AllowAnonymous]
- [Route("Register")]
- public async Task<IHttpActionResult> Register(RegisterBindingModel model)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
- IdentityResult result = await UserManager.CreateAsync(user, model.Password);
- if (!result.Succeeded)
- {
- return GetErrorResult(result);
- }
- return Ok();
- }
Response
- 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.
- [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
- [Route("UserInfo")]
- public UserInfoViewModel GetUserInfo()
- {
- ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
- return new UserInfoViewModel
- {
- Email = User.Identity.GetUserName(),
- HasRegistered = externalLogin == null,
- LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
- };
- }
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:
- config.Routes.MapHttpRoute
- (
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
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,
- public IEnumerable<string> GetValues()
- {
- return new string[] { "Hello", "Web API" };
- }
We can also customize the routing in above action method like,
- [HttpGet]
- public IEnumerable<string> Valuelist()
- {
- return new string[] { "Hello", "Web API" };
- }
- config.Routes.MapHttpRoute
- (
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{action}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
For example consider the following action method in the Values Controller:
- [HttpGet]
- public IEnumerable<string> Valuelist()
- {
- return new string[] { "Hello", "Web API" };
- }
- [ActionName("TestList")]
- public IEnumerable<string> Valuelist()
- {
- return new string[] { "Hello", "Web API" };
- }
Response of /api/values/TestList API
- public static void Register(HttpConfiguration config)
- {
- config.MapHttpAttributeRoutes();
- }
Attribute routing can be combined with convention based routing. To define convention-based routes, call the MapHttpRoute method.
- public static void Register(HttpConfiguration config)
- {
- // Web API routes
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- [HttpGet]
- [Route("api/valuesList/{id:int}")]
- public string Get(int id)
- {
- return "The entered ID is: " + id;
- }
- [RoutePrefix("api/ValuesList")]
- public class ValuesController : ApiController
- {
- // GET api/values
- [HttpGet]
- [Route("")]
- public IEnumerable<string> Valuelist()
- {
- return new string[] { "Hello", "Web API" };
- }
- // GET api/values/5
- [HttpGet]
- [Route("{id:int}")]
- public string Get(int id)
- {
- return "The entered ID is: " + id;
- }
- }
- [HttpGet]
- [Route("~/api/ OverrideList/{id:int}")]
- public string Get(int id)
- {
- return "The entered ID is: " + id;
- }
- [HttpGet]
- [Route("{name}")]
- public string GetName(string name)
- {
- return "The entered string is: " + name;
- }

- [HttpGet]
- [Route("{date:DateTime}")]
- public string GetDate(DateTime date)
- {
- return "The entered date is: " + date;
- }
- [HttpGet]
- [Route("{name}")]
- [NonAction]
- public string GetName(string name)
- {
- return "The entered string is: " + name;
- }
Response of api/ValuesList/Hello
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.

Arul RPosted Jan 17, 2016, 10:48 AM
Thanks for nice article
Humayun Kabir MamunPosted Dec 28, 2015, 2:01 AM
Nice...
Sibeesh VenuPosted Dec 25, 2015, 10:15 AM
Nice Share
Raja TPosted Dec 25, 2015, 1:45 AM
Nice,Thanks for sharing
Santhakumar MunuswamyPosted Dec 25, 2015, 12:55 AM
Thanks for nice article. Keep it up
Sridhar SharmaPosted Dec 24, 2015, 11:10 PM
Nice Share