Restful Server&Client Demo


Server端

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace ApiServer
{
    [ServiceContract(Name = "PersonInfoQueryServices")]
    public interface IPersonInfoQuery
    {
        [OperationContract]
        [WebGet(UriTemplate = "PersonInfoQuery/{name}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        User GetScore(string name);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "PersonInfoQuery/Info", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        User GetInfo(Info info);
    }


    [DataContract]
    public class User
    {
        [DataMember]
        public int ID;

        [DataMember]
        public string Name;

        [DataMember]
        public int Age;

        [DataMember]
        public int Score;
    }
    [DataContract]
    public class Info
    {
        [DataMember]
        public int ID;

        [DataMember]
        public string Name;
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Threading.Tasks;

namespace ApiServer
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PersonInfoQueryServices : IPersonInfoQuery
    {
        private List UserList = new List();
        public PersonInfoQueryServices()
        {
            UserList.Add(new User() { ID = 1, Name = "张三", Age = 18, Score = 98 });
            UserList.Add(new User() { ID = 2, Name = "李四", Age = 20, Score = 80 });
            UserList.Add(new User() { ID = 3, Name = "王二麻子", Age = 25, Score = 59 });
        }
        public User GetScore(string name)
        {
            return UserList.FirstOrDefault(x => x.Name == name);
        }
        public User GetInfo(Info info)
        {
            return UserList.FirstOrDefault(x => x.ID == info.ID && x.Name == info.Name);
        }


    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace ApiServer
{
    class Program
    {
        static void Main(string[] args)
        {
            PersonInfoQueryServices service = new PersonInfoQueryServices();
            Uri baseAddress = new Uri("http://127.0.0.1:7788");
            WebServiceHost _serviceHost = new WebServiceHost(service, baseAddress);
            _serviceHost.Open();
            Console.WriteLine("Web服务已开启...");
            Console.WriteLine("输入任意键关闭程序!");
            Console.ReadKey();
            _serviceHost.Close();

        }
    }
}

Client端

using System.IO;
using System.Net;
using System.Text;

namespace ApiClient
{
    public class RestClient
    {
        public string EndPoint;
        /// 
        /// 请求方式
        /// 
        public EnumHttpVerb Method;
        /// 
        /// 文本类型(1、application/json 2、txt/html)
        /// 
        public string ContentType;
        /// 
        /// 请求的数据(一般为JSon格式)
        /// 
        public string PostData;

        public RestClient() : this("")
        { }
        public RestClient(string endpoint) : this(endpoint, EnumHttpVerb.Get)
        { }
        public RestClient(string endpoint, EnumHttpVerb method, string postData = "")
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "application/json";
            PostData = postData;
        }

        /// 
        /// http请求(带参数)
        /// 
        /// parameters例如:?name=LiLei
        /// 
        public string HttpResult(string parameters)
        {
            var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;
            if (!string.IsNullOrEmpty(PostData) && Method == EnumHttpVerb.Post)
            {
                var bytes = Encoding.UTF8.GetBytes(PostData);
                request.ContentLength = bytes.Length;
                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var resonseValue = string.Empty;
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = string.Format("请求数据失败. 返回的 HTTP 状态码:{0}", response.StatusCode);
                    return "";
                }

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            resonseValue = reader.ReadToEnd();
                        }
                    }
                }

                return resonseValue;
            }


        }
    }

    public enum EnumHttpVerb
    {
        Get,
        Post,
        Put,
        Delete
    }
}

客户端调用

class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Restful客户端Demo测试";

            RestClient client = new RestClient();
            client.EndPoint = "http://127.0.0.1:7788/";
            client.Method = EnumHttpVerb.Get;
            var ret = client.HttpResult("PersonInfoQuery/张三");
            Console.WriteLine("GET方式获取结果:" + ret);


            Dictionary<string, object> param = new Dictionary<string, object>();
            param.Add("ID", 1);
            param.Add("Name", "张三");
            client.Method = EnumHttpVerb.Post;
            client.PostData = JsonConvert.SerializeObject(param);
            ret=client.HttpResult("PersonInfoQuery/Info");
            Console.WriteLine("POST方式获取结果:" + ret);
            Console.Read();
        }
    }