三种客户端访问wcf服务端的方法 C#

 string jsonstr = String.Empty;
            string url = "http://localhost:7041/Service1/Hello";
            #region WebClient 访问Get
            WebClient webclient = new WebClient();
            Uri uri = new Uri(url, UriKind.Absolute);
            if (!webclient.IsBusy)
            {
                webclient.Encoding = System.Text.Encoding.UTF8;
                jsonstr = webclient.DownloadString(url);
                dynamic json = JsonHelper.Deserialize(jsonstr);
                if (json.Length > 0)
                {
                    this.Label1.Text = json[0]["StringValue"] + ">>>" + json[0]["Id"] + "WebClientGet";
                }

            }
            #endregion
            #region WebClient 访问Post
            url = "http://localhost:7041/Service1/GetList";
            IDictionary data = new Dictionary
			{
				{"stringValue", "汉字汉字"}  
			};
            byte[] postData = Encoding.UTF8.GetBytes(JsonHelper.Serialize(data));
            WebClient clienttt = new WebClient();
            clienttt.Headers.Add("Content-Type", "application/json");
            clienttt.Headers.Add("ContentLength", postData.Length.ToString());
            byte[] responseData = clienttt.UploadData(url, "POST", postData);
            string rr = Encoding.UTF8.GetString(responseData);
            dynamic jsontt = JsonHelper.Deserialize(rr);
            if (jsontt["GetListResult"].Length > 0)
            {
                this.Label1.Text = jsontt["GetListResult"][0]["StringValue"] + ">>>" + jsontt["GetListResult"][0]["Id"] + "WebClientGetPost";
            }
            #endregion

            #region WebRequest Get 访问
            url = "http://localhost:7041/Service1/Hello";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            string code = response.ContentType;
            code = code.Split('=')[1];
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream, Encoding.GetEncoding
                    (code));
                string retemp = sr.ReadToEnd();
                dynamic jsonretemp = JsonHelper.Deserialize(retemp);
                if (jsonretemp.Length > 0)
                {
                    this.Label1.Text = jsonretemp[0]["StringValue"] + ">>>" + jsonretemp[0]["Id"] + "WebRequest Get";
                }

            }
            response.Close();
            #endregion
            #region WebRequest Post 访问
            url = "http://localhost:7041/Service1/GetList";
            WebRequest requestPost = WebRequest.Create(url);
            requestPost.Method = "POST";
            byte[] postDatarequestPost = Encoding.UTF8.GetBytes(JsonHelper.Serialize(data));
            requestPost.ContentType = "application/json";
            requestPost.ContentLength = postDatarequestPost.Length;
            Stream dataStream = requestPost.GetRequestStream();
            dataStream.Write(postDatarequestPost, 0, postDatarequestPost.Length);
            dataStream.Close();
            WebResponse responsePost = requestPost.GetResponse();
            dataStream = responsePost.GetResponseStream();
            StreamReader readerPost = new StreamReader(dataStream, Encoding.UTF8);
            string ResponseFromServer = readerPost.ReadToEnd();
            dynamic jsonttResponseFromServer = JsonHelper.Deserialize(ResponseFromServer);
            if (jsonttResponseFromServer["GetListResult"].Length > 0)
            {
                this.Label1.Text = jsonttResponseFromServer["GetListResult"][0]["StringValue"] + ">>>" + jsonttResponseFromServer["GetListResult"][0]["Id"] + "WebRequestPost";
            }
            readerPost.Close();
            dataStream.Close();
            responsePost.Close();
            #endregion
            
            #region HttpClient Get访问
            url = "http://localhost:7041/Service1/Hello";
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage message = client.Get(url))
                {
                    message.EnsureStatusIsSuccessful();
                    jsonstr = message.Content.ReadAsString();
                    dynamic json = JsonHelper.Deserialize(jsonstr);

                    if (json.Length > 0)
                    {
                        this.Label1.Text = json[0]["StringValue"] + ">>>" + json[0]["Id"] + ">>>>HttpClientGet";
                    }
                }
            }
            #endregion
            #region HttpClient Post 访问
            url = "http://localhost:7041/Service1/GetList";
            HttpClient clientPost = new HttpClient();
            clientPost.DefaultHeaders.Add("ContentType", "application/json");
            clientPost.DefaultHeaders.Add("Accept", "application/json");

            HttpContent content = HttpContent.Create(JsonHelper.Serialize(data), Encoding.UTF8, "application/json");
            HttpResponseMessage responseMessage = clientPost.Post(url, content);
            if (responseMessage.StatusCode != HttpStatusCode.OK && responseMessage.StatusCode != HttpStatusCode.Accepted)
            {
                //出错
            }
            responseMessage.EnsureStatusIsSuccessful();
            string result = responseMessage.Content.ReadAsString();
            dynamic jsonpost = JsonHelper.Deserialize(result);

            if (jsonpost["GetListResult"].Length > 0)
            {
                this.Label1.Text = jsonpost["GetListResult"][0]["StringValue"] + ">>>" + jsonpost["GetListResult"][0]["Id"] + ">>>>HttpClientPost";
            }
            #endregion

服务端代码要注意配置属性,比如

[WebInvoke(UriTemplate = "GetList", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)]

每种属性的意义搞清楚

你可能感兴趣的:(asp.net)