Attribute routing is very helpful when you are trying to customize the response behavior of your RESTful application. For this article example, we will take advantage of the Attribute Routing by performing some filtering at the back end by decorating the method in the controller. Below are the code to show the implementation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Constants For Authorization Features | |
public static class SampleRole | |
{ | |
public const string HR = "HumanResource"; | |
public const string Sales = "Sales"; | |
} | |
// Simple Attribute Routing | |
[RoutePrefixAttribute("api/publicaccess")] | |
public class SampleController : ApiController | |
{ | |
[Route("{id}")] | |
[AllowAnonymous] | |
public string GetDataPublic() | |
{ | |
return "Perform algorithm to hide all Sensitive data"; | |
} | |
[Route("{id}/hr")] | |
[Authorize(Roles = SampleRole.HR)] | |
public string GetDataForHRUsers() | |
{ | |
return "Perform algorithm to show HR related data" ; | |
} | |
[Route("{id}/sales")] | |
[Authorize(Roles = SampleRole.Sales)] | |
public string GetDataForSalesUsers() | |
{ | |
return "Perform algorithm to show Sales data "; | |
} | |
} |
Based on the code, we may now able to give the caller some options on how the response going to be. Assuming the caller is a Manager, which hold the role for HR and Sales. The caller (manager) will be able to make use of the Attribute Routing to pick which response he/she would prefer.If he/she would like to :
1.Get all public data - The Manager may call
http://localhost:26374/api/publicaccess/65
2.Get data related to HR - The Manager may call
http://localhost:26374/api/publicaccess/65/hr
3.Get data related to Sales - The Manager may call
http://localhost:26374/api/publicaccess/65/sales
Conclusion
Based on the example, with Web API 2 we now may perform some sort like a basic filtering on how to response to client calls.
Back - Web Application > Web Api
Published on : 13-Jan-2018
Ref no : DDN-WPUB-000038
About Author

Comments
Post a Comment