接下来进入的是俺在ASP.NET学习中最重要的WebAPI部分,在现在流行的互联网场景下,WebAPI可以和HTML5、单页应用程序SPA等技术和理念很好的结合在一起。所谓ASP.NET WebAPI,其核心概念就是构建REST风格的Web服务,把一起数据视为资源,无论是服务请求或者是数据操作,与以前的SOAP和XML-RPC架构风格有很大不同。说道这,很多读者可能想到WCF中不是早都有了REST风格的服务么,为什么还需要这个WebAPI?确实如此,不过WCF中的该类型服务显得比较复杂,因为其通信管道的构成由于集成了多种不同的通信协议,自然的其基础程序集就显得非常的庞大臃肿。

    简单来说,WebAPI就是简单高效,"你值得拥有"!让我们通过临摹蒋老师的例子对它有个初步的了解,后端代码如下:

 1 public class ContactsController : ApiController
 2 {
 3 private static IList<Contact> contacts = new List<Contact>
 4 {
 5 new Contact{
 6 Id="001",
 7 Name="Xixi",
 8 PhoneNo="12132432",
 9 EmailAddress="xixi@gmail.com"
10 },
11 new Contact{
12 Id="002",
13 Name="XiongEr",
14 PhoneNo="312",
15 EmailAddress="XiongEr@gmail.com"
16 }
17 };
18 public IEnumerable<Contact> Get()
19 {
20 return contacts;
21 }
22 public Contact Get(string id)
23 {
24 return contacts.FirstOrDefault(c => c.Id == id);
25 }
26 public void Put(Contact contact)
27 {
28 contact.Id = Guid.NewGuid().ToString();
29 contacts.Add(contact);
30 }
31 public void Post(Contact contact)
32 {
33 Delete(contact.Id);
34 contacts.Add(contact);
35 }
36 public void Delete(string id)
37 {
38 Contact tempContact = contacts.FirstOrDefault(c => c.Id == id);
39 contacts.Remove(tempContact);
40 }
41 }
View Code

相关文章:

  • 2021-08-28
  • 2021-08-15
  • 2021-07-20
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-03-08
  • 2022-12-23
相关资源
相似解决方案