zoukankan      html  css  js  c++  java
  • wcf rest 服务用于安卓和ISO调用1

      最近项目中需要编写一个服务,以供安卓和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 上传文件....

  • 相关阅读:
    每日日报
    每日日报
    每日日报
    线上问题定位---jstack
    8.18Java入门--->第二十二节(ObjectOutputStream、ObjectInputStream)
    8.17Java入门--->第二十一节(IO流)
    Mybatis--->第六节一对多和多对一
    8.14Java入门--->第二十节
    8.13Java入门--->第十九节(Map嵌套)
    Java学习
  • 原文地址:https://www.cnblogs.com/yt-007/p/5176727.html
Copyright © 2011-2022 走看看