The contact Manager web API is an Asp.net web API sample program that demonstrates the use of ASP. net web API exposes contact information and allows you to add and delete contacts, sample address http://code.msdn.microsoft.com/Contact-Manager-Web-API-0e8e373d. the following article uses this example to explain ASP. net web API knowledge:
1. CRUD operation: curd is short for "Create, read, update, delete" (ADD, read, update, delete). These four actions are basic operations of the database.
Web API crud method description |
ActionDescription |
HTTPMethod |
UriConnection |
Retrieve a list of all contacts |
Get |
/API/contacts |
Get contact data by ID |
Get |
/API/contacts/ID |
Add a contact |
Post |
/API/contacts |
Update contact data |
Put |
/API/contacts/ID |
Delete contact data |
Delete |
/API/contacts/ID |
From the above table, we can clearly see that there are two resource types ):
Uri Resource Type |
Uri |
Description |
/API/contacts |
List all contacts |
/API/contacts/ID |
One contact |
HTTPMethod
The main HTTP methods (get, put, post, delete) can correspond to the curd operation:
· GetReceiveAnd display. Get should have no side effects on the server.
· PutUpdate. Put can also be used"New"Use, if the server allows the client to specify a new Uri. In this example, contact management cannot be added using put.
· PostNew. The server assigns a new object to the URI and returns the URI as part of the response message.
· DeleteDelete.
Add resources
In ASP. NET Web APIs, you can use strong-type CLR objects in the model. They will be automatically serialized as XML or JSON to the client. InModelDirectoryOfContactClass:
Public class contact
{
Public int contactid {Get; set ;}
Public string name {Get; set ;}
Public String address {Get; set ;}
Public String city {Get; set ;}
Public String state {Get; set ;}
Public String zip {Get; set ;}
Public String email {Get; set ;}
Public String Twitter {Get; set ;}
Public String self
{
Get {return string. Format (cultureinfo. currentculture, "contact/{0}", this. contactid );}
Set {}
}
}
Repository Pattern)
Our HTTP service needs to store the contact list. In this example, the contact list is stored in the memory (List (of T)). Using repository pattern will cut this object out of our service instance. InModelDirectory, AddInterface, NameIcontactrepository. CS
Public interface icontactrepository
{
Void Update (contact updatedcontact );
Contact get (int id );
List <contact> getall ();
Void post (contact );
Void Delete (int id );
}
The above defines the required crud-related functional interfaces.ModelDirectoryAdd a new class file, class file"Contactrepository. CS", This class will be implementedIcontactrepositoryInterface. Implementation is as follows:
Public class contactrepository: icontactrepository
{
Private int nextcontactid;
Private ilist <contact> contacts;
Public contactrepository ()
{
Contacts = new list <contact> ();
Contacts. add (new contact {contactid = 1, name = "Glenn Block", address = "1 Microsoft Way", city = "Redmond", state = "Washington ", zip = "98112", email = "gblock@microsoft.com", Twitter = "gblock "});
Contacts. add (new contact {contactid = 2, name = "Howard dierking", address = "1 Microsoft Way", city = "Redmond", state = "Washington ", zip = "98112", email = "howard@microsoft.com", Twitter = "howard_dierking "});
Contacts. add (new contact {contactid = 3, name = "yavor Georgiev", address = "1 Microsoft Way", city = "Redmond", state = "Washington ", zip = "98112", email = "yavorg@microsoft.com", Twitter = "digthepony "});
Contacts. add (new contact {contactid = 4, name = "Jeff Handley", address = "1 Microsoft Way", city = "Redmond", state = "Washington ", zip = "98112", email = "jeff.handley@microsoft.com", Twitter = "jeffhandley "});
Contacts. add (new contact {contactid = 5, name = "deepesh mohnani", address = "1 Microsoft Way", city = "Redmond", state = "Washington ", zip = "98112", email = "deepm@microsoft.com", Twitter = "deepeshm "});
Contacts. add (new contact {contactid = 6, name = "Brad olenick", address = "1 Microsoft Way", city = "Redmond", state = "Washington ", zip = "98112", email = "brado@microsoft.com", Twitter = "brado_23 "});
Contacts. add (new contact {contactid = 7, name = "Ron jacbs", address = "1 Microsoft Way", city = "Redmond", state = "Washington ", zip = "98112", email = "rojacobs@microsoft.com", Twitter = "ronljacbs "});
Nextcontactid = contacts. Count + 1;
}
Public void Update (contact updatedcontact)
{
VaR contact = this. Get (updatedcontact. contactid );
Contact. Name = updatedcontact. Name;
Contact. Address = updatedcontact. address;
Contact. City = updatedcontact. City;
Contact. State = updatedcontact. State;
Contact. Zip = updatedcontact. Zip;
Contact. Email = updatedcontact. Email;
Contact. Twitter = updatedcontact. Twitter;
}
Public contact get (int id)
{
Return contacts. singleordefault (C => C. contactid = ID );
}
Public list <contact> getall ()
{
Return contacts. tolist ();
}
Public void post (contact)
{
Contact. contactid = nextcontactid ++;
Contacts. Add (contact );
}
Public void Delete (int id)
{
VaR contact = this. Get (ID );
Contacts. Remove (contact );
}
}
There is no difficulty in implementation.List (of contacts)Provided. Add (),. Remove (),. Find ()To add, delete, and query operations. In addition,. Asqueryable ()To convert the list type.Iqueryable ()Back and forth. The above uses the list to simulate the database, or think of the list as a database in the memory.
Web API controller (contactscontroller)
Contactscontroller is the program code of the HTTP service.HTTP method, mainly because the conventions are better than the configuration concept.. "Conventions" are rules. Rules are pre-defined. Engineers only need to follow the rules and do not need additional "configurations ". Of course, it can also be different. You can also use httpmothod to tag.
Obtain resources
Read andGet. Two actions are provided in contact management. One is to read all contacts, and the other is to obtain contacts by ID. Both actions are defined inHTTP GETMethod. Remember that the method must start with "get.
· Get/API/contacts
· Get/API/contacts/ID
Add resources
The newly added resources are create andPost. To add a new contact, the client sends an http post request. The request information contains the relevant content of the new contact. Remember that the method must start with "post.
Public httpresponsemessage <contact> post (contact)
{
This. repository. Post (contact );
VaR response = new httpresponsemessage <contact> (contact) {statuscode = httpstatuscode. Created };
String uri = URL. Route ("default", new {id = contact. contactid });
Response. headers. Location = new uri (request. requesturi, Uri );
Return response;
}
The default parameter is from the request body.DeserializationFollowed by the composite (complex) type. Therefore, what we expect the client to send to us isSerializationRepresents the contact object, serialized using XML or JSON. The above two things are taken into account:
·Response Code
By default, the status code of the returned status is set to 200 (OK) in the web API framework ). However, according to the HTTP/1.1 protocol, when a POST request causes resource establishment, the server should respond to the status code 201 (created ).
·LocationWhen the Server adds a resource, it should include the URI of the new resource in the response Location header.
Note that the return type isHttpresponsemessage (of contact),Httpresponsemessage (of T)A type is an HTTP response message with a strong type. Generic parametersTThe CLR type is obtained and serialized to the information body.
Update Resources
Update resources arePut. It is intuitive to update a contact. Remember that the method must start with "put.
Public contact put (int id, contact)
{
Contact. contactid = ID;
This. repository. Update (contact );
Return contact;
}
The method has two parameters: Contact ID and updated contact data. The ID parameter is obtained from the URI path, and the contact parameter is serialized from the request body. By default, ASP. NET web API framework obtains a simple parameter type from the route and composite (complex) types in the Request body.
Delete Resource
Deleting a resource is a combination of Delete andDelete.
Public httpresponsemessage Delete (int id)
{
VaR deleted = This. repository. Get (ID );
This. repository. Delete (ID );
Return new httpresponsemessage (httpstatuscode. nocontent );
}
According to the HTTP specification, the delete method must be idmpotent (idempotent ),It means several identicalUriMust have the same effect as a Delete request.. Therefore, if the contact has been deleted, the method should not return the error code.
If the Delete request is successful, you can return the status 200 (OK) to describe the status of the entity body (that is, the entity to be deleted), or if the deletion persists and the status 202 (accepted) is not processed ), or no entity returns status 204 (NO content ). In our example, Status 204 (NO content) is returned ).
CrudOperation Summary
When using ASP. net web API framework, you can find that there is a lot of link with the HTTP/1.1 specification, the content that was seldom concerned with and understood before, such as put, delete, post processing, and the processing of status code.