The ambition of WCF makes it huge and complex, and HTTP makes it simple and beautiful. To implement distributed Web applications, we have to combine the two. The WCF Service is bound to the host in IIS over HTTP.
As a result, configuration is confusing and debugging is depressing, and ServiceContract, DataContract, EnumMember... Also, do not call the WCF Service in the using statement...
So I often asked myself: Is it necessary to take a knife to cut an apple? No. Where is the fruit knife?
Microsoft looked at so many people with a knife to cut the apple, they could not see it, so a fruit knife was born-ASP. NET Web API.
Recently, in actual development, it was too troublesome to use WCF. I tried a little fruit knife and it felt pretty good.
The following is a simple example to share the usage of the ASP. NET Web API fruit knife.
Implementation of ASP. NET Web API on the server
Tools to be prepared: Visual Studio 2010, NuGet
1. Create an empty ASP. NET Web Application project.
2. add ASP. NET Web API reference, use "AspNetWebApi" (use "ASP. NET Web API), and then select ASP.. NET Web API (Beta) for installation.
3. Add Global. asax, register the Web API route in Application_Start, and add the following code to Global. asax. cs:
protected void Application_Start(object sender, EventArgs e){ RouteTable.Routes.MapHttpRoute("WebApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });}
4. Add the Controllers folder, add the class file DemoController. cs, And let DemoController inherit from ApiController. The Code is as follows:
namespace CNBlogsWebApiDemo.Controllers{ public class DemoController : ApiController { }}
5. Add the ViewModels folder, add Site. cs, and define Site.
namespace CNBlogsWebApiDemo.ViewModels{ public class Site { public int SiteId { get; set; } public string Title { get; set; } public string Uri { get; set; } }}
6. Add a method SiteList to DemoController and write our sample code. The Code is as follows:
Public class DemoController: ApiController {public IList <Site> SiteList (int startId, int itemcount) {var sites = new List <Site> (); sites. add (new Site {SiteId = 1, Title = "test", Uri = "www. cnblogs. cc "}); sites. add (new Site {SiteId = 2, Title = "", Uri = "www.cnblogs.com"}); sites. add (new Site {SiteId = 3, Title = "blog", Uri = "q.cnblogs.com"}); sites. add (new Site {SiteId = 4, Title = "news", Uri = "news.cnblogs.com"}); sites. add (new Site {SiteId = 5, Title = "", Uri = "job.cnblogs.com"}); var result = (from Site site in sites where site. siteId> startId select site ). take (itemcount ). toList (); return result ;}}
7. Configure the startup settings of the Web project Specific Page and Specific port
8. Press Ctrl + F5 to run the project. The result is as follows:
The results are expected. You can use a browser to directly view the running results of Web APIs, which is convenient during testing.
Now, the server Web API is so easy!
The client calls the Web API of the server through HttpClient.
1. Create a WebApiTest class library project.
2. Add System. Net. Http (HttpClient is here), Json. NET, and xUnit.net to NuGet.
3. Add the class file WebApiClientTest. cs and add the test method WebApi_SiteList_Test:
namespace WebApiClientTest{ public class WebApiClientTest { [Fact] public void WebApi_SiteList_Test() { } }}
4. WebApi_SiteList_Test () code implementation
4.1 first, determine three things:
A) The client calls WebAPI through Http Get and Http Post. Here we use Http Post;
B) The parameter format passed when the client calls WebAPI. Here Json is used.
C) The format of the data returned by WebAPI. Here we use Json (this is also the reason why Json. NET was referenced before ).
4.2 classes used
- System. Net. Http. HttpClient
- System. Net. Http. httpContent
- System. Net. Http. StringContent
- System. Net. Http. Headers. MediaTypeHeaderValue
- Newtonsoft. Json. JsonConvert
4.3 prepare parameters to be passed to WebAPI
The two parameters to be passed are startId and itemcount. The format is Json. No JSON. stringify () in Javascript is available here, but we have Json. NET, coupled with the anonymous type. The Code is as follows:
var requestJson = JsonConvert.SerializeObject(new { startId = 1, itemcount = 3 });
Code running result: {"startId": 1, "itemcount": 3}
Use System. Net. Http. StringContent to pack it:
HttpContent httpContent = new StringContent(requestJson);
Set ContentType:
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
4.4 call WebAPI through Http Post to get the returned results
HttpClient debuted and called its PostAsync () method to easily handle it:
var httpClient = new HttpClient();var responseJson = httpClient.PostAsync("http://localhost:9000/api/demo/sitelist", httpContent) .Result.Content.ReadAsStringAsync().Result;
Take a look at the responseJson result:
[{"SiteId": 2, "Title": "blog homepage", "Uri": "www.cnblogs.com" },{ "SiteId": 3, "Title ": "Bo Wen", "Uri": "q.cnblogs.com" },{ "SiteId": 4, "Title": "news", "Uri": "news.cnblogs.com"}]
Authentic Json! You have noticed that the WebAPI code on the server has not been modified. We set ContentType to application/json in Http Headers, and the returned data is in Json format. What we get is standard XML when we access it through a browser. This is one of the charms of ASP. NET Web APIs-one-time implementation and on-demand service.
4.5 deserialize the results returned in Json format to a strong type
Json. NET was launched again:
var sites = JsonConvert.DeserializeObject<IList<Site>>(responseJson);
The returned results are as follows:
Code
sites.ToList().ForEach(x => Console.WriteLine(x.Title + ":" + x.Uri));
Result
Blog homepage: www.cnblogs.com blog: q.cnblogs.com news: news.cnblogs.com
4.6 complete WebApi_SiteList_Test () implementation code
public class WebApiClientTest{ [Fact] public void WebApi_SiteList_Test() { var requestJson = JsonConvert.SerializeObject(new { startId = 1, itemcount = 3 }); HttpContent httpContent = new StringContent(requestJson); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var httpClient = new HttpClient(); var responseJson = httpClient.PostAsync("http://localhost:9000/api/demo/sitelist", httpContent) .Result.Content.ReadAsStringAsync().Result; var sites = JsonConvert.DeserializeObject<IList<Site>>(responseJson); sites.ToList().ForEach(x => Console.WriteLine(x.Title + ":" + x.Uri)); }}
Note: before running the code, you must first run the WebAPI project and run the service before the client can enjoy the service.
Compared with the jQuery ajax call code:
var requestJson = JSON.stringify({ startId: 1, itemcount: 3 });$.ajax({ url: '/api/demo/sitelist', data: requestJson, type: "post", dataType: "json", contentType: "application/json; charset=utf8", success: function (data) { jQuery.each(data, function (i, val) { $("#result").append(val.Title + ': ' + val.Uri +'<br/>'); }); }});
Note: The actual code is available. The code is in the ajaxwebapi.htm file of the demonstration code webapidemo. This is also the embodiment of "one-time implementation and on-demand service" for ASP. NET Web APIs.
Summary
The use of the fruit knife (ASP. NET Web API) is not only good, but also can cut the apple, also can cut the pear, cut the watermelon is also easy to talk about. It is much more important to consider using the WCF.
Download Sample Code
Http://files.cnblogs.com/dudu/CNBlogsWebApiDemo.rar
Update
Wahaha ABC raised a very good question:
WebApiTest references WebApiDemo. Is it a distributed application that implements a strong type?
The powerful Json. NET can easily solve this problem, and the code is changed:
// Original code: var sites = JsonConvert. deserializeObject <IList <Site> (responseJson); var sites = JArray. parse (responseJson); sites. toList (). forEach (x => Console. writeLine (x ["Title"] + ":" + x ["Uri"]);