Create a Web API project
The first step is to create the following items
Of course, you can also create a Web API project that leverages the Web API template, and the Web API template uses ASP. NET MVC to provide the help page for the API.
Add model
A model is an object that presents data in your application. The ASP. NET Web API can automatically serialize your model to json,xml or some other format, and then write the serialized data to the body of the HTTP response message. As long as the client can read the serialized data, it can also deserialize the object. Most clients can parse JSON or XML. Additionally, the client can declare the format of the receive header that it wants to set through the HTTP request message.
Then we create a simple model of the display product in the models directory
namespace webapidemo.models{public class Product {public int Id {get; set;} public string Name {get; set;} public string Category {get; set;} Public decimal price {get; set;}} }
Add Repository
First we need to store a collection of products, separate the phone our service is a good idea, in this way, we can change the backup storage, without modifying the server implementation, this model is called the storage model, the first to establish an interface
Namespace webapidemo.models{public interface iproductrepository { ienumerable<product> GetAll () ; Product Get (int id); Product ADD (product item); void Remove (int id); BOOL Update (Product item);} }
For the time being, we put the interface and implementation class in a directory, now add another class under the models directory, this class will implement the Iproductrepository interface
1 namespaceWebapidemo.models2 {3 Public classproductrepository:iproductrepository4 {5 Privatelist<product> products =NewList<product>();6 Private int_nextid =1;7 Publicproductrepository ()8 {9ADD (NewProduct {Name ="One plus 5", Category ="One plus", Price =2999 });TenADD (NewProduct {Name ="Xiaomi Pro", Category ="Millet", Price =5599 }); OneADD (NewProduct {Name ="One plus x", Category ="One plus", Price =1499 }); A } - PublicProduct ADD (product item) - { the if(Item = =NULL) - Throw NewArgumentNullException ("Item"); -Item. Id = _nextid++; - Products . ADD (item); + returnitem; - } + A PublicProduct Get (intID) at { - returnProducts. Find (y = = Y.id = =ID); - } - - PublicIenumerable<product>GetAll () - { in returnProducts ; - } to + Public voidRemove (intID) - { theProducts. RemoveAll (y = y.id = =ID); * } $ Panax Notoginseng Public BOOLUpdate (Product Item) - { the if(Item = =NULL) + Throw NewArgumentNullException ("Item"); A intindex = products. FindIndex (y = y.id = =item. ID); the if(Index <0) + return false; - Products . RemoveAt (index); $ Products . ADD (item); $ return true; - } - } the}
Add Controller
In the ASP. NET Web API, the controller is an object that handles HTTP requests. We will add a controller that can return the list data for an item, or return individual product information through the product number.
Note that if you use ASP. NET MVC is familiar with the controller, the WEB API controller is similar to the MVC controller, but inherits Apicontroller instead of the controller class
1 namespace webapidemo.controllers 2 {3 Public class Productcontroller:apicontroller 4 {5 staticnew productrepository (); 6 }7 }
Basic how to add crud
First: Get a list of all product listings and add the method to the controller as follows
1 Public Ienumerable<product> getproducts ()2 {3 return Repository. GetAll (); 4 }
This method starts with get, so it maps a GET request by convention, and because it does not contain parameters, it maps a URI that does not contain the ID field in the path
The second method: To obtain a product information by product number, add the following method in the controller
1 PublicProduct GetProduct (intID)2 {3 varitem =Repository. Get (ID);4 if(Item = =NULL)5 //thrown a 404 status code exception not found6 Throw New 7 httpresponseexception (httpstatuscode.notfound);8 returnitem;9}
The name of this method begins with a get, but this method has a parameter named ID. This parameter is mapped to the ID field in the URI path. The ASP. NET WEB API framework automatically converts the ID parameter to the correct int data type, and throws an Httpresponseexception exception if the ID is invalid. This exception will have a frame converted to a 404 error.
Third: Find product information by type, and add the method to the controller as follows
1 Public Ienumerable<product> getproductsbycategory (string category)2{3 return repository. GetAll (). Where (y = string.equals (y.category, Category, StringComparison.OrdinalIgnoreCase)); 4 }
If the requested URI contains a query string, the Web API attempts to match the query string in the parameters of the Controller method. Therefore, the URI of "Api/products?category=category" in the form is mapped to this method.
Fourth: Add a new product, add the following method to the controller
1 Public Product Postproduct (product item) 2 {3 item = Repository. ADD (item); 4 return item; 5 }
Note Two things about this method:
The name of this method begins with "Post", in order to create a new product, the client sends an HTTP POST request. This method takes a parameter of type product. In the Web API, the parameters of a complex type are deserialized from the body of the request message, so we expect the client to send the sequence number representation of a product object in XML or JSON format
This implementation works, but it's not complete. Ideally, we want the HTTP response. Contains the following content:
Response code: By default, the Web API framework sets the response status code to (OK). But according to this http/1.1 protocol, when the post request is creating a resource, the server should revert to the status 201 (Created). Location: When a server creates a resource, it should include the URI of the resource in the address header of the response.
The ASP. NET Web API makes it easy to manipulate HTTP response messages. This improved code:
Publichttpresponsemessage postproduct (Product Item) {Item=Repository. ADD (item); //creates a return object Httpresposemessage and sets the reply status to 201.Httpresponsemessage respose = request.createresponse<product>(httpstatuscode.created, item); String URI= Url.link ("Defaultapi",New{id =item. Id}); //set Httpresposemessage header in LocaionRespose. Headers.location =Newuri (URI); returnrespose;}
Please note: This method return type is now httpresponsemessage. By returning Httpresponsemessage instead of the product, we can control the HTTP response message, including the status code and the details of the location header.
The Createresponse method creates a httpresponsemessage and automatically writes the Product object serialization representation to the body of the response message.
Fourth one: New products by put
1 Public void Putproduct (int id,product product)2{3 product. id = ID; 4 if (! Repository. Update (product))5 thrownew httpresponseexception ( Httpstatuscode.notfound); 6 }
The method name begins with a put so that the Web API can match it to a put request. This method has two parameters, one is the product ID and the updated product, the ID parameter is obtained from the URI, and the product parameter is deserialized from the request body. By default, the ASP. NET WEB API framework gets a simple parameter type from the route, fetching complex types from the request body.
Fifth method: Delete the product, add the code below the controller.
1 public void Deleteproduct (int ID) 2 { 3 Product Item =
repository. Get (ID);
4
if (item = =
null
)
5
throw
new
Httpresponseexception (httpstatuscode.notfound);
6
repository. Remove (ID);
7 }
If the deletion succeeds, it can return a status of (OK) with the description of the entity that State, or if the delete is still pending, returns status 202 (accepted), or the state with no entity body 204 (no content). In this case, the Deleteproduct method has a void return type, so the ASP. NET Web API automatically translates this status code 204 (no content)
Run Tests
Once the method is created, we can run the server and test it.
In this test we found that our route was only "Api/{controler}" and successfully returned the data in the GetProducts method, which is the difference between the ASP. The Web API route can have no {Action}, only the HTTP request to match the route, and the route defaults to API revelation, and if you want to set it, set the route in the Webapiconfig class in App_start.
ASP. NET Web API (ii)