1. 程式人生 > >WCF服務支援HTTP(get,post)方式請求例子

WCF服務支援HTTP(get,post)方式請求例子

https://www.cnblogs.com/li150dan/p/9529413.html

 

        /// <summary>
        /// Http Get請求
        /// </summary>
        /// <param name="url">請求地址</param> 
        /// <param name="postData">請求引數</param> 
        /// <param name="result">返回結果</param>
        /// <returns></returns>
        public static bool WebHttpGet(string url, string postData, out string result)
        {
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + (postData == "" ? "" : "?") + postData);
                httpWebRequest.Method = "GET";
                httpWebRequest.ContentType = "text/html;charset=UTF-8";

                WebResponse webResponse = httpWebRequest.GetResponse();
                HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;
                System.IO.Stream stream = httpWebResponse.GetResponseStream();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, Encoding.GetEncoding("UTF-8"));
                result = streamReader.ReadToEnd(); //請求返回的資料
                streamReader.Close();
                stream.Close();
                return true;
            }
            catch (Exception ex)
            {
                result = ex.Message;
                return false;
            }
        }

        /// <summary> 
        /// Http Post請求
        /// </summary> 
        /// <param name="url">請求地址</param> 
        /// <param name="postData">請求引數</param> 
        /// <param name="result">返回結果</param>
        /// <returns></returns> 
        public static bool WebHttpPost(string url, string postData, out string result)
        {
            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);

                string RequestUrl = url + postData;
                HttpWebRequest httpWebRequest = WebRequest.Create(RequestUrl) as HttpWebRequest;
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength = byteArray.Length;

                using (System.IO.Stream stream = httpWebRequest.GetRequestStream())
                {
                    stream.Write(byteArray, 0, byteArray.Length);                  
                }

                HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                using (System.IO.Stream responseStream = httpWebResponse.GetResponseStream())
                {
                    System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                    result = streamReader.ReadToEnd(); //請求返回的資料
                    streamReader.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                result = ex.Message;
                return false;
            }
        }
複製程式碼

//-------------WCF服務端web.config配置如下:----------------

複製程式碼
 <system.serviceModel>    
    <services>
      <service name="WCFService.WebUser">
        <!--WCF中提供了Web HTTP訪問的方式-->
        <endpoint binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="WCFService.IWebUser" />
        <!--提供WCF服務 , 注意address='Wcf',為了區分開與Web HTTP的地址,新增引用之後會自動加上的-->
        <endpoint address="Wcf" binding="basicHttpBinding" contract="WCFService.IWebUser"/>
      </service>
    </services>
    <behaviors>
      <!--WCF中提供了Web HTTP的方式-->
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <!--WCF中提供了Web HTTP的方式-->
      <serviceBehaviors>
        <behavior>
          <!-- 為避免洩漏元資料資訊,請在部署前將以下值設定為 false -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- 要接收故障異常詳細資訊以進行除錯,請將以下值設定為 true。在部署前設定為 false 以避免洩漏異常資訊 -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
複製程式碼

//-------------WCF服務-------------

複製程式碼
namespace WCFService
{
    // 注意: 使用“重構”選單上的“重新命名”命令,可以同時更改程式碼和配置檔案中的介面名“IWebUser”。
    [ServiceContract]
    public interface IWebUser
    {
        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/ShowName?name={name}")]
        string ShowName(string name);

        [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/ShowNameByPost/{name}")]
        string ShowNameByPost(string name);
    }
}
複製程式碼

//-----------客戶端傳統方式和web http方式呼叫----------------

複製程式碼
    public static void Main(string[] args)
        {                   
            WebUserClient webUser = new WebUserClient();
            Console.WriteLine("請輸入姓名!");
            string webname = Console.ReadLine();
            string webresult = webUser.ShowName(webname);
            Console.WriteLine(webresult);

            Console.WriteLine("請輸入姓名!");
            string getData = Console.ReadLine();
            string apiGetUrl = "http://localhost:8423/WebUser.svc/ShowName";
            string jsonGetMsg = string.Empty;
            bool strGetResult = WebHttpGet(apiGetUrl, "name=" + getData, out jsonGetMsg);
            Console.WriteLine("請求結果:" + strGetResult + ",返回結果:" + jsonGetMsg);

            Console.WriteLine("請輸入姓名!");
            string postData = Console.ReadLine();
            string apiPostUrl = "http://localhost:8423/WebUser.svc/ShowNameByPost";
            string jsonPostMsg = string.Empty;
            bool strPostResult = WebHttpPost(apiPostUrl, "/" + postData, out jsonPostMsg);
            Console.WriteLine("請求結果:" + strPostResult + ",返回結果:" + jsonPostMsg);
            Console.ReadLine();
        }
複製程式碼