Web API Series (i): the applicable scenario for the Web API, the first instance

Source: Internet
Author: User
Tags response code

In my previous blog has given you a brief introduction of the HTTP protocol and RESTful API relationship, as well as some basic HTTP protocol knowledge, in this knowledge, today, we discuss the application of the Web API scenario, and then write our first Web API interface, and shows how to make a simple call to it.

A lot of people are confused, now that you have WCF, why do you have a Web API? Will the WEB API replace WCF?

In my opinion, WCF provides a collection of RPC implementations, and WCF's design takes more account of SOA scenarios, as well as the various RPC issues. Many people will also say that the RESTful API is also a kind of RPC ah, and WCF also has the implementation of the restful AH. There are a lot of data RPC and restful in the style concept is some difference, in fact, I think the difference between the two more subjective, over-tangled these on the College School; I focused on some of the issues that are actually used, in WCF, the many protocols supported, the WS-* series protocols, and some more concise protocols, The performance of some dedicated communication protocols is very high, and WCF provides features such as service discovery, and I think WCF is better suited for high-performance calls between internal systems, and there are other RPC scenarios in the community that can be chosen, such as Grpc,avor,thrift, which are the same products that WCF locates , while the Web API is focused on the HTTP restful style of the product, on this basis, any language, any terminal can be very easy to docking, and can take advantage of a very sophisticated variety of HTTP infrastructure and solutions for development, debugging, load balancing, content distribution. So, the WEB API is an HTTP-oriented development framework that focuses on the rapid development of restful, open-style APIs. At the moment, he does not replace WCF, they each have a suitable scenario, and cannot assume that the Web API is a substitute for WCF.

OK, now let's develop the first set of Web API interfaces! With VS2012 later versions have a ready-made WEB API to create templates, you can create it, after the project will have MVC, Web API project, the Web API to MVC is dependent, can not be created alone! Both the Web API and MVC use a similar routing mechanism, so in the default route, the Web API uses the

/api/{controller}/{id}

As a route, the/api/section is added to differentiate between MVC and Web APIs.

Next, we add a controller for the Web API named PersonController, which he inherits from Apicontroller; When we create this controller, we define a resource: person, All operations in PersonController revolve around the resource of person. Next we begin to define a set of additions and deletions to the operation.

In the Web API, the default route takes on a convention: to route according to a predicate, and the prefix of the method name is to invoke the HTTP verb used by the method. The code examples are as follows:

/// <summary>    ///Person is a resource, a set of actions on person/// </summary>     Public classPersoncontroller:apicontroller {Private StaticList<person> _personlst =NewList<person>(); /// <summary>        ///get a person/// </summary>        /// <param name= "id" >ID of person</param>        /// <returns> Person</returns>         PublicPerson Getperson (LongID) {return_personlst.find (x = X.id = =ID); }         /// <summary>        ///Add a person/// </summary>        /// <param name= "Person" > Person</param>         Public voidPostaddperson (person person) {_personlst.add (person); }         /// <summary>        ///Modify a/// </summary>        /// <param name= "id" >Person Id</param>        /// <param name= "Person" >New</param>         Public voidPutmodifyperson (LongID, person person) {            varp = _personlst.find (x = X.id = =ID); P.age=Person .            Age; P.name=Person .            Name; P.sex=Person .        Sex; }         /// <summary>        ///Delete a person/// </summary>        /// <param name= "id" >Person ID</param>         Public voidDeleteperson (LongID) {_personlst.removeall (x= = X.id = =ID); }}

A simple API for resource-based CRUD operations, no parsing input, no splicing output, is that simple! Let's take a walk!

Send request: predicate is post, semantic creation Person,person description in body, head declares body through JSON serialization.

Received response: Response code 204, belongs to the 2XX type successful execution, no data in the body

Send request: Predicate is get, semantics for query person resource, ID 1, head declared want to receive data serialized with XML

Received response: Response code is 200, execution succeeds, body has data, data is serialized using XML

Send request: The predicate is put, the semantics is to modify the person resource ID 1, modify the content in the body, Content-type marked body using JSON serialization, in the body we change the name to Test1changed

Received response, Response Code 204, execution succeeded

Send request: Predicate is get, semantics is query ID 1 person resource, accept indicates want to receive JSON data

Received response: You can see the body is serialized with JSON content, the Name property has changed to Test1changed

Send request: Verb is delete, semantics is delete person resource with ID 1

Received response: Response code 204, execution succeeded

Send request: Predicate is get, semantics is query ID 1 person resource, accept indicates want to receive JSON data

Received response: Response code is 200, execution succeeded, response content is null, resource deleted

This is what I use Fiddler to send, call a set of restful interfaces, you can see that the entire call process using the HTTP semantics, using the predicate routing, content negotiation. In the increment, delete, change operation, I use void as the return value, according to HTTP Code judgment, you can also customize some of the return data to make a further operation description.

After writing these APIs, we need to call them in the program, and I'll write a set of implementations of these interface calls in C # as an example. In C #, there are generally two ways to call HTTP interfaces: Webrequest/webresponse combined method calls and WebClient classes. The first method is less abstract and cumbersome to use, while WebClient is mainly oriented to Web page scenes, which is more convenient when simulating web operations, but it is cumbersome to use in restful scenes while the Web API is published. Net provides two assemblies: System.Net.Http and System.Net.Http.Formatting. The most central class of these two assemblies is httpclient. In. NET4.5 with both assemblies, and. NET4 need to download Microsoft.Net.Http and Microsoft.AspNet.WebApi.Client in NuGet to use this class, the lower. Net version can only be regretted with webrequ Est/webresponse or WebClient to invoke these APIs.

In use, System.Net.Http This assembly provides httpclient classes and related Http calls, and System.Net.Http.Formatting provides some help extensions for httpclient, which better supports content negotiation, Content creation and other functions. Let me write this example with you:

We create a new console program:

The code is as follows:

 Public classPerson { Public LongId {Get;Set; }  Public stringName {Get;Set; }  Public intAge {Get;Set; }  Public stringSex {Get;Set; }  Public Override stringToString () {return$"Id={id} name={name} age={age} Sex={sex}"; }    }     classProgram {Static voidMain (string[] args) {            varClient =NewHttpClient (); Client. BaseAddress=NewUri ("http://localhost:22658/");//Basic API URLclient. DEFAULTREQUESTHEADERS.ACCEPT.ADD (NewMediatypewithqualityheadervalue ("Application/json"));//default desired response using JSON serializationRun (client);         Console.ReadLine (); }         Static Async voidRun (HttpClient client) {varresult =awaitAddperson (client); Console.WriteLine ($"Add result: {result}");//Add Result: True             varperson =awaitGetperson (client); Console.WriteLine ($"Query result: {person}");//Search Result: id=1 name=test age=10 sex=fresult=awaitPutperson (client); Console.WriteLine ($"Update result: {result}");//Update Result: Trueresult=awaitDeleteperson (client); Console.WriteLine ($"Delete result: {result}");//Delete Result: true        }         Static Asynctask<BOOL>Addperson (HttpClient client) {return awaitClient. Postasjsonasync ("Api/person",NewPerson () {age =Ten, Id =1, Name ="Test", Sex ="F"})//send a POST request to person, the body is serialized using JSON                                     . ContinueWith (x= X.result.issuccessstatuscode);//returns whether the request was successfully executed, that is, whether HTTP code is 2XX        }         Static AsyncTask<person>Getperson (HttpClient client) {return await awaitClient. Getasync ("API/PERSON/1")//send a GET request to person                . ContinueWith (x= X.result.content.readasasync<person> (//gets the body returned, and deserializes the body according to the returned Content-type auto-match formatter                    NewList<mediatypeformatter> () {NewJsonmediatypeformatter ()/*This is the JSON formatter.*/                                                    ,NewXmlmediatypeformatter ()/*This is the XML formatter*/})); }         Static Asynctask<BOOL>Putperson (HttpClient client) {return awaitClient. Putasjsonasync ("API/PERSON/1",NewPerson () {age =Ten, Id =1, Name ="Test1change", Sex ="F"})//send a put request to person and the body is serialized using JSON                                    . ContinueWith (x= X.result.issuccessstatuscode);//returns whether the request was successfully executed, that is, whether HTTP code is 2XX        }         Static Asynctask<BOOL>Deleteperson (HttpClient client) {return awaitClient. Deleteasync ("API/PERSON/1")//send a delete request to person                . ContinueWith (x= X.result.issuccessstatuscode);//returns whether the request was successfully executed, that is, whether HTTP code is 2XX        }}

Web API Series (i): the applicable scenario for the Web API, the first instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.