using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography.X509Certificates;

namespace CallWcfRest
{
    public class UserInfo
    {
        public string userName { get; set; }
        public string userPassword { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //客户端证书的处理
            X509Certificate2 cert = GetX509Certificate();
            string dataUrl = Properties.Settings.Default["DataUrl"].ToString();
            string loginUrl = Properties.Settings.Default["LoginUrl"].ToString();
            bool isAnoymous = true;
            Console.WriteLine("请输入用户名:");
            string user = Console.ReadLine();
            Console.WriteLine("请输入密码:");
            string pwd = Console.ReadLine();
            UserInfo info = new UserInfo
            {
                userName = user,
                userPassword = pwd
            };
            //先访问LoginService，得到授权
            var request = (HttpWebRequest)WebRequest.Create(loginUrl);
            request.ContentType = "application/json;charset=utf-8";
            request.Method = "POST";
            request.KeepAlive = true;
            //request.ClientCertificates.Add(cert);
            //使用JSON.NET将对象序列化成JSON字符串
            var requestBody = JsonConvert.SerializeObject(info);
            byte[] databytes = Encoding.UTF8.GetBytes(requestBody);
            request.ContentLength = databytes.Length;
            using (var writer = request.GetRequestStream())
            {
                writer.Write(databytes, 0, databytes.Length);
            }
            var response = request.GetResponse();
            var encryptedCookie = response.Headers["Set-Cookie"];
            using (var stream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    if (reader.ReadToEnd() == "true")
                    {
                        Console.WriteLine("登录成功");
                        isAnoymous = false;
                    }
                }
            }
            //如果未能通过Forms身份验证
            if (isAnoymous)
            {
                Console.WriteLine("登录失败");
                return;
            }
            //访问DataService
            var request1 = (HttpWebRequest)WebRequest.Create(dataUrl);
            request1.Method = "GET";
            request1.Headers["Cookie"] = encryptedCookie;
            var response1 = request1.GetResponse();
            using (var stream = response1.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    string res = reader.ReadToEnd();
                    //使用JSON.NET进行反序列化
                    var obj = JsonConvert.DeserializeObject<dynamic>(res);
                    Console.WriteLine("......你将得到数据.....");
                    Console.WriteLine(obj[1].StringValue);
                }
            }
        }

        private static X509Certificate2 GetX509Certificate()
        {
            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "MyEggSoft", false);
            return certs[0];
        }
    }
}
