Webapi as a platform for the construction of a restful period of time, plus the recent use, so want to record their own experience. I will take a simple deletion and modification as the opening.
Get ready
The definition of the entity class (figure).
public class Figure {public string FirstName {get; set;} public string LastName {get; set;} }
Then define a static class Figuremanager to store the figure collection to manipulate.
public static class Figuremanager { static list<figure> figures; Static Figuremanager () { figures = new list<figure> (); Figures. ADD (New figure ("Eddard", "Stack")); Figures. ADD (New figure ("Robb", "Stack")); Figures. ADD (New figure ("Sansa", "Stack")); Figures. ADD (New figure ("Arya", "Stack")); Figures. ADD (New figure ("Bran", "Stack")); Figures. ADD (New figure ("Rickon", "Stack")); Figures. ADD (New figure ("Jon", "Snow"); } public static list<figure> figures { get {return figures;} }
Crud
In general, we may be operating the addition and deletion of the change, so the demo I use these basic operations (because the changes and new actions in the front-end results are similar, so there is no example of writing changes).
Query All (GET)
public IEnumerable<figure> GetAll ()
This method I will Figuremanager. Figures returns as a result.
Querying via FirstName (GET)
Here I use two types of communication: QueryString and Route
QueryString
Public figure getbyquerystring (string firstName)
Url:http://localhost:4296/api/figure/getbyquerystring?firstname=bran
Route:
[Route("Api/figure/getbyroute/{firstname}")]
Public figure getbyroute (string firstName)
Url:http://localhost:4296/api/figure/Getbyroute/bran
New (POST)
For the new, since the figure class has only two properties, the four methods used in the demo (for easy viewing of each method will be Figuremanager. Figures as the return value):
- Get Firstname,lastname directly
public IEnumerable<figure> Postbyurl (string firstName, string LastName)
Url:http://localhost:4296/api/figure/postbyurl?firstname=catelyn&lastname=tully
- model binding via QueryString
public IEnumerable<figure> Postbyurlmodel (figure )
Url:http://localhost:4296/api/figure/postbyurlmodel?firstname=catelyn&lastname=tully
Model binding via the route
[Route("Api/figure/postbyroutemodel/{firstname}/{lastname}")]
public IEnumerable<figure> Postbyroutemodel (figure )
Url:http://localhost:4296/api/figure/postbyroutemodel/catelyn/tully
- transfer model through body
public IEnumerable<figure> Postbybody ([frombody] figure )
Url:http://localhost:4296/api/figure/postbybody
Body
{
"FirstName": "Catelyn",
"LastName": "Tully"
}
Remove (delete)
Because HTTP provides a way to delete requests, it is deleted directly using the delete request:
public IEnumerable<figure> Delete (string firstName)
Url:http://localhost:4296/api/figure/delete?firstname=catelyn
Source
Github:https://github.com/barlowdu/webapi
ASP. WebAPI 01-demo