Skip to main content

WebAPI - Attribute Routing Based On Parameter Type - Basic

My photo
There will come into a certain situation where we might encounter parameter issue when implementing Web Api methods in a specific controller. This is usually happen when we wanted to make use of an overloaded technique in our Web Api methods. For example

Notice that the method name is the same but the method is able to compile since its an overloaded method.
The problem arise when the code is deployed and being called by clients .
Below are the call that will return with error.
Request
GET http://localhost:48795/api/backendata/678 HTTP/1.1
Response
HTTP/1.1 400 Bad Request ......

Next we are trying to hit the second method by sending a parameter with a string type.
Request
GET http://localhost:48795/api/backendata/foo HTTP/1.1
Response
HTTP/1.1 400 Bad Request ......

This is due to the fact that there is a conflict for the engine to determine to use parameter as an int or a string, the code will raise an exception that return a bad request response.
Luckily Asp.Net Web Api 2 has a workaround if we experience this situation during development. The solution is by implementing an attribute-constrained-based routing. From the code above we may decorate a route attribute and pass in the data type to let the WebApi engine to determine on how to anticipate the route request. Whatever reason behind the requirement, taking advantage of overloaded method in Web API is possible, this is true by implementing the attribute-constrained-based routing

Now we try to hit the controller again after we decorate the method with attribute-based routing technique Request
GET http://localhost:48795/api/backendata/678 HTTP/1.1
Response
HTTP/1.1 200 OK ......(Return int algorithm)

Next we are trying to hit the second method by sending a parameter with a string type.
Request
GET http://localhost:48795/api/backendata/foo HTTP/1.1
Response
HTTP/1.1 4HTTP/1.1 200 OK .....(Return string algorithm)

Next we try to hit with a mixture of int and string for example 678foo. The engine will treat the parameter as a string. Request
GET http://localhost:48795/api/backendata/foo1234 HTTP/1.1
Response
HTTP/1.1 HTTP/1.1 200 OK .....(Return string algorithm)


Back - Web Application > Web Api

Published on : 13-Jan-2018
Ref no : DDN-WPUB-000037

About Author

My photo
Wan Mohd Adzha MCPD,MCSD,MCSE
I am passionate about technology and of course love Durians. Certified by Microsoft as MCP Since 2011. Blogging from Malaysia

Comments