wcf rest 服務用於安卓和ISO調用1

來源:互聯網
上載者:User

標籤:

  最近項目中需要編寫一個服務,以供安卓和iOS調用.現在記錄一下過程.(第一次寫部落格啊,潛水好久了......)

  wcf 具體的東西就不多說啦.上步驟和代碼....

  首先建立一個wcf項目,建立一個實體類.代碼如下

  

  [DataContract]    public class Users    {        [DataMember]        public string Id { get; set; }        [DataMember]        public string Name { get; set; }        [DataMember]        public int Gender { get; set; }    }

  然後在介面中編寫一些get和post方法.

[OperationContract]        [WebGet(UriTemplate = "GetUsers",           ResponseFormat = WebMessageFormat.Json)]        [System.ComponentModel.Description("擷取全部使用者")]        ICollection<Users> GetUsers();        [OperationContract]        [WebGet(UriTemplate = "GetUserById/{id}",           ResponseFormat = WebMessageFormat.Json)]        [System.ComponentModel.Description("根據id擷取使用者")]        Users GetUserById(string id);        [OperationContract]        [WebInvoke(Method = "POST", UriTemplate = "AddUser",            ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]        [System.ComponentModel.Description("添加使用者")]        Users AddUser(Users news);

  實現介面方法,代碼如下:

 private ICollection<Users> _listCollection = new List<Users>()        {            new Users()            {                Id = "1",Gender=1,Name="張無忌"            }, new Users()            {                Id = "2",Gender=2,Name="張三丰"            }, new Users()            {                Id = "3",Gender=1,Name="任盈盈"            },        };        public ICollection<Users> GetUsers()        {            return _listCollection;        }        public Users GetUserById(string id)        {            return _listCollection.FirstOrDefault(v => v.Id == id);        }        public Users AddUser(Users news)        {            _listCollection.Add(news);            return news;        }

  最後在設定檔中加入如下代碼:

<system.serviceModel>    <bindings>      <webHttpBinding>        <binding name="webBinding"  closeTimeout="00:40:00" receiveTimeout="00:40:00" sendTimeout="00:40:00"maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" useDefaultWebProxy="false" >          <security mode="None"></security>          <readerQuotas maxDepth="32" maxArrayLength="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="2147483647"/>        </binding>      </webHttpBinding>    </bindings>    <services>      <service name="WcfServiceTest.Service1" behaviorConfiguration="wgjServiceBehavior">        <endpoint address="" behaviorConfiguration="webBehavior"                  binding="webHttpBinding" bindingConfiguration="webBinding" contract="WcfServiceTest.IService1">        </endpoint>      </service>    </services>    <behaviors>      <endpointBehaviors>        <behavior name="webBehavior">          <!--這裡必須設定-->          <webHttp helpEnabled="true"/>        </behavior>      </endpointBehaviors>      <serviceBehaviors>        <behavior name="wgjServiceBehavior">        </behavior>      </serviceBehaviors>    </behaviors>  </system.serviceModel>

  加上helpEnabled="true"並且在介面上加上System.ComponentModel.Description可在介面地址後面加上/help瀏覽方法說明.效果如

 

  

 

最後我們建立一個控制台應用程式來測試介面. 

 在項目中添加NuGet程式包中添加Http Client庫:

現在開始編寫方法:

        private static async void GetUserById(string id)        {            Console.WriteLine("-----------根據id擷取使用者----------");            HttpClient httpClient = new HttpClient();            var result = await httpClient.GetStringAsync("http://localhost:31572/Service1.svc/getUserById/1");            Console.WriteLine(result);        }        private static async void GetUsers()        {            Console.WriteLine("-----------擷取所有使用者----------");            HttpClient httpClient = new HttpClient();            var result = await httpClient.GetStringAsync("http://localhost:31572/Service1.svc/GetUsers");            Console.WriteLine(result);        }        public static async void AddUser()        {            Console.WriteLine("------------添加使用者-----------------");            HttpClient httpClient = new HttpClient();            var jobj = new JObject();            jobj["Id"] = "4";            jobj["Name"] = "大師兄";            jobj["Gender"] = 1;            string str = jobj.ToString();            HttpContent content = new StringContent(str);            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");            var response = await httpClient.PostAsync("http://localhost:31572/Service1.svc/AddUser", content);            response.EnsureSuccessStatusCode();//錯誤引發異常            Console.WriteLine(response.Content.ReadAsStringAsync().Result);        }

  最後,這次就寫到這裡.下次是使用wcf rest 上傳檔案....

 

wcf rest 服務用於安卓和ISO調用1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.