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

來源:互聯網
上載者:User

標籤:cli   ati   ESS   pac   tps   bin   http post   異常   oid   

        /// <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();        }

 

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.