How to create WebAPI using Attributerouting for Custom URL?

In this blog, Aegis Software developers will help ASP.NET Development Company and development community to create WebAPI step-by-step using Attributerouting for custom URL. This post will make them more proficient in development of WebAPI and saves their time.

Following are the steps to create MVC WebAPI using Attribute Routing with Custom URL.

1. Open VS and select new Project ASP.NET MVC 4 Web application and select Web API as Project Template, give appropriate project name like “Sample.WebAPI” (Note: I have black mark in all images are projectname) then click ok. It will create WebAPI project with two default controllers HomeController and ValuesController.

2. Delete HelpPage folder form Areas folder as we do not want to use it. You can keep it if you wish to have list of web methods displayed there.

3. Right click on References folder and add references of the following dll files.

  • AttributeRouting.dll
  • AttributeRouting.Web.dll
  • AttributeRouting.Web.Http.dll
  • AttributeRouting.Web.Http.WebHost.dll
  • WebActivator.dll
  • WebGrease.dll

Note: if you don’t find these dlls then you can search “AttributeRouting for MVC WebAPI” in NuGet package manager to install for your visual studio.

4. As we are using Nhibernate (with SimpleInjector) concept, we need to provide necessary DLL references for that. After that add two folders into Model folder.

  • Configuration
  • Mappings

5. Create one xml file into Configuration folder and give the name hibernate.cfg.xml. paste following code into the file. This is Nhibernet configuration file which contains connection string and other information.

<?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="connection.provider"> NHibernate.Connection.DriverConnectionProvider </property> <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> <property name="connection.driver_class"> NHibernate.Driver.SqlClientDriver </property> <property name="connection.connection_string"> “your date base connection string” </property> <property name="show_sql">true</property> <property name="current_session_context_class">web</property> </session-factory> </hibernate-configuration>

Note: I am creating webservices like GetAllUsers, GetRegisterUser, CreateRegisterUser, UpdateRegisterUser, DeleteRegisteUser, GetLoginUser and GetUserByUserName for RegisterUser table.

6. Create Mapping file for the RegisterUser table like in following image and give the name RegisterUser.hbm.xml.

Create Mapping

7. Create new “AttributeRoutingHttpConfig.cs” into App_Start folder like in this image.


8. Create “Registeruser.cs” into Models folder like this image.


9. Create Repository folder in root and add class file into it and create methods for RegisterUser table like following which are useful to call from RegisteruserController.

  • GetRegisterUsers
  • GetRegisterUserByUserID
  • GetUserByUserNamePassword
  • GetUserByUserName
  • CreateRegisterUser
  • UpdateRegisterUser
  • DeleteRegisterUser

10. Right click on Controllers and add Controller named “RegisterUserController.cs” 11. Inherit RegisterUserController class with ApiController(for this class you have to add AttributeRouting.Web.Http namespace). 12. Add following code into RegisterUSerController.cs.

//This method will return all RegisterUsers. [HttpGet] [GET("registeruser/get")] public HttpResponseMessage GetAllUsers() { List <Registeruser> list = repo.GetRegisterUsers(); var response = Request.CreateResponse <List> <Registeruser> (HttpStatusCode.OK, list); return response; } //This method will return RegisterUser by ID in form of HttpResponseMessage. [HttpGet] [GET("registeruser/get/{id}")] public HttpResponseMessage GetRegisterUser(int id) { Registeruser item = repo.GetRegisterUserByUserID(id); var response = Request.CreateResponse <Registeruser> (HttpStatusCode.Found, item); return response; } //This method will create RegisterUser. [HttpPost] [POST("registeruser/create")] public HttpResponseMessage CreateRegisterUser(Registeruser item) { if (ModelState.IsValid) { bool r = repo.CreateRegisterUser(item); if (r) { var response = Request.CreateResponse <Registeruser> (HttpStatusCode.Created, item); return response; } else return Request.CreateResponse(HttpStatusCode.BadRequest); } else return Request.CreateResponse(HttpStatusCode.BadRequest, "Failed validation !! Please check user object for valid data."); } //This method will update RegisterUser record by its ID. [HttpPost] [POST("registeruser/update")] public HttpResponseMessage UpdateRegisterUser(Registeruser user) { if (ModelState.IsValid) { if (!repo.UpdateRegisterUser(user)) { return Request.CreateResponse(HttpStatusCode.BadRequest); } else return Request.CreateResponse <Registeruser> (HttpStatusCode.OK, user); } else return Request.CreateResponse(HttpStatusCode.BadRequest, "Failed validation !! Please check user object for valid data."); } //This method will delete RegisterUser record by its ID. [HttpGet] [GET("registeruser/delete/{id}")] public HttpResponseMessage DeleteRegisterUser(int id) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest); if (id <=0 ) return response; bool r=r epo.DeleteRegisterUser(id); if (r) return Request.CreateResponse(HttpStatusCode.OK, id); else return response; ; } //This method will return RegisterUser record by username and password. [HttpGet] [GET( "registeruser/getloginuser/{username}/{*password}")] public HttpResponseMessage GetLoginUser(string username, string password) { Registeruser user=r epo.GetUserByUserNamePassword(username, password); var response=R equest.CreateResponse <Registeruser> (HttpStatusCode.Found, user); return response; } //This method will return RegisterUser By username to check unique username. [HttpGet] [GET("registeruser/getloginuser/{username}/{*password}")] public HttpResponseMessage ValidateLogin(string username, string password) { Registeruser user = repo.validateLogin(username, password); var response = Request.CreateResponse <Registeruser> (HttpStatusCode.Found, user); return response; }

Now you can access these methods in URL

like, http://localhost/registeruser/get and http://localhost/registeruser/create and so on. Here, http://localhost is the locally configured path and /registeruser/get/{id} where id is the UserId field to get that particular record. The path is what we defined in [Get] attribute at top of every controller method. And That's done.

You can now access all web api methods on your custom URL. The other benefit of attributerouting is we can define as many parameters as we want. Check the last web API method "ValidateLogin" which has {username} and {*password} as parameters where * means that parameter can't be ignored.

The post is been shared by Aegis Software developers to assist .NET developers and development community in developing WebAPI utilizing attributerouting for custom url.

For further information, mail us at