WCF Web API Preview 5 发布了,你可以官方网站下载或通过Nuget安装它. 下面让我们在Asp.net applicatoin中来实现一个非常简单的web api service.

在VS中打开Package Manage Console下,输入:

Install-Package WebApi.All     

然后我们创建Contact与其实现类:

   1:      /// <summary>
   2:      /// a simple Contact entity
   3:      /// </summary>
   4:      public class Contact
   5:      {
   6:          /// <summary>
   7:          /// Name
   8:          /// </summary>
   9:          public string Name { get; set; }
  10:      }  
  11:   
  12:      [ServiceContract]
  13:      public interface IContactsResource
  14:      {
  15:          [WebGet(UriTemplate = "")]
  16:          List<Contact> Get();
  17:      }
  18:   
  19:      /// <summary>
  20:      /// Demo for host a web.api in asp.net application
  21:      /// </summary>
  22:      /// <remarks>author Petter Liu http://www.cnblogs.com/wintersun </remarks>
  23:      public class ContactsResource :IContactsResource
  24:      {
  25:          /// <summary>
  26:          /// Get list of Contacts
  27:          /// </summary>
  28:          /// <returns>list of contacts</returns>
  29:          public List<Contact> Get()
  30:          {
  31:              return new List<Contact>()
  32:             { 
  33:                new Contact() { Name = "Peter" } 
  34:             };
  35:          }
  36:      }

代码很简单.然后在Global.asax中Application_Start增加如下代码:

   1:          void Application_Start(object sender, EventArgs e)
   2:          {
   3:              RouteTable.Routes.MapServiceRoute<ContactsResource>("contacts"); 
   4:          }

接着打开浏览器运行吧,访问http://localhost:7287/contacts , 得到这样的结果:

  <?xml version="1.0" encoding="utf-8" ?> 
    <ArrayOfContact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"             xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <Contact>
        <Name>Peter</Name> 
     </Contact>
  </ArrayOfContact>

让我们再用UnitTest来验证一下, 引用HttpClient库.

   1:          [TestMethod]
   2:          public void TestGetAction()
   3:          {
   4:              //arrange
   5:              var client = new HttpClient();
   6:   
   7:              //act
   8:              var resp = client.Get("http://localhost:7287/contacts");
   9:   
  10:              //assert
  11:              Assert.IsTrue(resp.IsSuccessStatusCode);
  12:   
  13:              var contacts = resp.Content.ReadAs<List<Contact>>();
  14:              Assert.IsNotNull(contacts);
  15:              Assert.AreEqual("Peter", contacts.FirstOrDefault().Name);
  16:          }

OK,Pass. 一切就是那么简单

希望这篇POST对您开发WCF有帮助.

 

您可以感兴趣的文章:

使用WCF web API测试基于REST的WCF Service


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on 2011-09-21 14:44  PetterLiu  阅读(659)  评论(0编辑  收藏  举报