Back - Web Application > Web Api
There are 2 places that we may decide on how to handle our routing, although there are more sophisticated technique such as custom attribute, in this article we will discuss on 2 of the basic way to implement ASP.NET Web API routing.
1. At The Method
This file contains hidden or 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
public class InvoiceController : ApiController | |
{ | |
[Route("api/invoices/{id}")] | |
public Team GetInvoice(string id) | |
{ | |
//perform data access to get individual invoice based on its 'id' | |
} | |
[Route("api/invoices")] | |
public IEnumerable<Invoice> GetInvoice() | |
{ | |
//perform data access to get list invoice | |
} | |
[Route("api/invoices/{id}/items")] | |
public IEnumerable<Items> GetInvoices(string id) | |
{ | |
// perform data access to get list of items that is in a specific invoice based on 'id' | |
} | |
} |
1. Return Individual Invoice - http://localhost:xxxxxx/api/invoice/yyyy
where the 'xxxxxx' is the port and 'yyyy' is the invoice id.
2. Return All Invoice List - http://localhost:xxxxxx/api/invoices
3. Return Items In Invoices From Invoice ID - http://localhost:xxxxxx/api/invoice/yyyy/items
where the 'xxxxxx' is the port and 'yyyy' is the invoice id.
2. At The Controller
This file contains hidden or 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
[RoutePrefix("api/invoices")] | |
public class InvoiceController : ApiController | |
{ | |
[Route("{id}")] | |
public Team GetInvoice(string id) | |
{ | |
//perform data access to get individual invoice based on its 'id' | |
} | |
[Route] | |
public IEnumerable<Invoice> GetInvoice() | |
{ | |
//perform data access to get list invoice | |
} | |
[Route("{id}/items")] | |
public IEnumerable<Player> GetInvoices(string id) | |
{ | |
// perform data access to get list of items that is in a specific invoice based on 'id' | |
} | |
} |
Conclusion
We may customize our routing using 2 basic technique, This technique is not an ideal solution but enough to show the features of Asp.Net Web API. There technique is error prone if the production solution might have a lot of customized method that is implemented in a specific controller since the intellisense might not be able to capture the string that we provide in the attributes.
Back - Web Application > Web Api
Published on : 12-Jan-2018
Ref no : DDN-WPUB-000036
About Author

Comments
Post a Comment