在Asp.net应用程序中构建基于WCF Web.Api的服务
生活随笔
收集整理的這篇文章主要介紹了
在Asp.net应用程序中构建基于WCF Web.Api的服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
????? 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。
總結
以上是生活随笔為你收集整理的在Asp.net应用程序中构建基于WCF Web.Api的服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java编码规范 Code Conven
- 下一篇: 最老程序员创业札记:全文检索、数据挖掘、