• WCF服务支持HTTP(get,post)方式请求例子


    方式一:

        /// <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="postUrl">请求地址</param>
        /// <param name="postData">请求参数(json格式请求数据时contentType必须指定为application/json)</param>
        /// <param name="result">返回结果</param>
        /// <returns></returns>
        public static bool WebHttpPost(string postUrl, string postData, out string result, string contentType = "application/x-www-form-urlencoded")
        {
            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
    
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = contentType;
                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;
            }              
        }

    方式二: 

        /// <summary>
        /// Http Get请求
        /// </summary>
        /// <param name="url">请求地址</param> 
        /// <param name="postData">请求参数</param> 
        /// <param name="trackId">为防止重复请求实现HTTP幂等性(唯一ID)</param>
        /// <returns></returns>
        public static string SendGet(string url, string postData, string trackId)
        {
            if (string.IsNullOrEmpty(trackId)) return null; //trackId = Guid.NewGuid().ToString("N");
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + (postData == "" ? "" : "?") + postData);
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "text/html;charset=UTF-8";
            httpWebRequest.Headers.Add("track_id:" + trackId);
    
            WebResponse webResponse = httpWebRequest.GetResponse();
            HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;
            System.IO.Stream stream = httpWebResponse.GetResponseStream();
            System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, Encoding.UTF8);
            string result = streamReader.ReadToEnd(); //请求返回的数据
            streamReader.Close();
            stream.Close();
    
            return result;
        }
    
        /// <summary>
        /// Http Post请求
        /// </summary>
        /// <param name="postUrl">请求地址</param>
        /// <param name="postData">请求参数(json格式请求数据时contentType必须指定为application/json)</param>
        /// <param name="trackId">为防止重复请求实现HTTP幂等性(唯一ID)</param>
        /// <returns></returns>
        public static string SendPost(string postUrl, string postData, string trackId, string contentType = "application/x-www-form-urlencoded")
        {
            if (string.IsNullOrEmpty(trackId)) return null; //trackId = Guid.NewGuid().ToString("N");
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
    
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = contentType;
            httpWebRequest.ContentLength = byteArray.Length;
            httpWebRequest.Headers.Add("track_id:" + trackId);
    
            System.IO.Stream stream = httpWebRequest.GetRequestStream();
            stream.Write(byteArray, 0, byteArray.Length); //写入参数 
            stream.Close();
    
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            System.IO.StreamReader streamReader = new System.IO.StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            string result = streamReader.ReadToEnd(); //请求返回的数据
            streamReader.Close();
    
            return result;
        }
    
        /// <summary>
        /// 生成唯一标识符
        /// </summary>
        /// <param name="type">格式:N,D,B,P,X</param>
        /// <returns></returns>
        public static string GetGuid(string type = "")
        {
            //Guid.NewGuid().ToString();    // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12
            //Guid.NewGuid().ToString("N"); // e0a953c3ee6040eaa9fae2b667060e09 
            //Guid.NewGuid().ToString("D"); // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12
            //Guid.NewGuid().ToString("B"); // {734fd453-a4f8-4c5d-9c98-3fe2d7079760}
            //Guid.NewGuid().ToString("P"); // (ade24d16-db0f-40af-8794-1e08e2040df3)
            //Guid.NewGuid().ToString("X"); // {0x3fa412e3,0x8356,0x428f,{0xaa,0x34,0xb7,0x40,0xda,0xaf,0x45,0x6f}}
            if (type == "")
                return Guid.NewGuid().ToString();
            else
                return Guid.NewGuid().ToString(type);
        }
    View Code

     //-------------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();
       }
  • 相关阅读:
    Controlling behavior of existing services in system
    获取站点路径方法
    如何处理DataTable.Select();执行后重新排序的问题!
    ASP.NET 2.0 编程珠玑之五调试已创建好的代码
    Meal Scheduler in C#
    DHTML+Ajax? MXML+ActionScript? XAML+C#? 是巧合,还是必然?
    C#验证输入的是否数字
    Monitoring System Usage using Windows Service
    ADO.NET 2.0中的DataSet和DataTable
    使用asp.net 2.0和SQL SERVER 2005构建多层应用
  • 原文地址:https://www.cnblogs.com/li150dan/p/9529413.html
Copyright © 2020-2023  润新知