The ambition of WCF has caused its complexity, and the simplicity of HTTP makes it simple and beautiful. To implement distributed Web applications, we had to make a difference. The--WCF service is hosted on IIS with an HTTP binding.
So have a confusing configuration, let people depressed unceasingly debugging, also have that ServiceContract, DataContract, Enummember ... Also, do not invoke the WCF service in the using statement ...
So I often ask myself: is it necessary to take the sledgehammer to cut apples? Nonsense, of course not necessary, where is the fruit knife?
Microsoft looked at so many people holding sledgehammer Apple, they can not see, so, a fruit knife turned out--asp.net Web API.
Recently we in the actual development of a place with WCF too troublesome, small try a fruit knife, feel good.
Here's a simple example to share the use of the ASP. NET Web API Fruit knife.
Implementation of the service-side ASP. NET Web API
Tools to prepare: Visual Studio, NuGet
1. Create a new empty ASP. NET WEB Application project.
2. Add a reference to the ASP. NET Web API through NuGet, use "Aspnetwebapi" when searching in NuGet (which is not searchable with the "ASP. NET Web API"), and then select the ASP. NET Web API (Beta) to install.
3. Add Global.asax, register the route for the Web API in Application_Start, and add the following code to the 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 in it, 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 = "博问", Uri = "q.cnblogs.com" });
sites.Add(new Site { SiteId = 4, Title = "新闻", Uri = "news.cnblogs.com" });
sites.Add(new Site { SiteId = 5, Title = "招聘", Uri = "job.cnblogs.com" });var result = (from Site site in siteswhere site.SiteId > startIdselect site)
.Take(itemcount)
.ToList();return result;
}
}
7. Configure the Web project startup settings specific page and specific port
8. Ctrl+f5 run the project with the following results:
As a result, we expect to see the results of the Web API running directly in the browser, and it will be convenient to test.
Well, the server-side Web API is so easy to fix!
The client invokes the server-side web API via httpclient
1. Create a new Class library project for Webapitest.
2. Add System.Net.Http (httpclient right here) in NuGet, Json.NET, xunit.net.
3. Add the class file WebApiClientTest.cs, add the test method Webapi_sitelist_test:
namespace WebApiClientTest
{public class WebApiClientTest
{
[Fact]public void WebApi_SiteList_Test()
{
}
}
}
4. Code implementation of Webapi_sitelist_test ()
4.1 First, to determine three things:
A) The way the client calls Webapi is HTTP Get, also HTTP POST, we use HTTP POST here;
b) The parameter format passed when the client invokes Webapi, we use JSON here.
c) The data format returned by WEBAPI, which is also JSON (which is why we added the Json.NET reference 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 the parameters to be passed to Webapi
The two parameters that need to be passed are Startid, ItemCount, and the format passed is JSON. There is no JavaScript in the json.stringify (), but we have json.net, plus anonymous type, a bit with the sense of JS, the code is as follows:
var Requestjson = Jsonconvert.serializeobject (New {Startid = 1, itemcount = 3});
Operation result of the code: {"Startid": 1, "ItemCount": 3}
Then use a System.Net.Http.StringContent to pack it:
Httpcontent httpcontent = new Stringcontent (Requestjson);
Then set the contenttype:
HttpContent.Headers.ContentType = new Mediatypeheadervalue ("Application/json");
4.4 Get returned results via HTTP POST call WEBAPI
HttpClient is on the blink, calling its Postasync () method to easily fix:
var httpClient = new HttpClient (), var Responsejson = Httpclient.postasync ("Http://localhost:9000/api/demo/sitelist", httpcontent) . Result.Content.ReadAsStringAsync (). Result;
Take a look at the results of Responsejson:
[{"SiteId": 2, "title": "Blog Park Home", "uri": "www.cnblogs.com"},{"SiteId": 3, "title": "Bo Q", "uri": "q.cnblogs.com"},{"SiteId ": 4," Title ":" News "," Uri ":" News.cnblogs.com "}]
The Authentic json! You notice that there is no change in the code of the server WEBAPI, we just set the ContentType in HTTP headers to Application/json and return the data in JSON format. And we access it through the browser, and we get the standard XML. Here is one of the charms of the ASP-one implementation, on-demand service.
4.5 deserializing results returned in JSON format to strongly typed
Json.NET another debut:
var sites = jsonconvert.deserializeobject<ilist<site>> (Responsejson);
Show back the results:
Code
Sites. ToList (). ForEach (x = Console.WriteLine (X.title + ":" + X.uri));
Results
Blog home: www.cnblogs.com bo Q: q.cnblogs.com news: news.cnblogs.com
4.6 Webapi_sitelist_test () full 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 here, run the WEBAPI project first, run the service first, the client can enjoy the service.
Compare with jquery Ajax calling 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 code above is actually running well, the code is in the sample Code Webapidemo project's ajaxwebapi.htm file. This is also the ASP. NET Web API "one-time implementation, on-demand service" embodiment.
Summary
Fruit Knife (ASP) It feels good not only to peel apples, but also to sharpen pears and cut watermelons. With no sledgehammer (WCF), you have to think about it more.