WCF服务支持HTTP(get,post)

2021-05-12 03:28

阅读:453

标签:故障   服务   ada   span   request   ext   web   DPoS   console   

方式一:

技术图片
    /// 
    /// Http Get请求
    /// 
    /// 请求地址 
    /// 请求参数 
    /// 返回结果
    /// 
    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;
        }
    }
            
    /// 
    /// Http Post请求
    /// 
    /// 请求地址
    /// 请求参数(json格式请求数据时contentType必须指定为application/json)
    /// 返回结果
    /// 
    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;
        }              
    }
技术图片

方式二: 

技术图片
技术图片
    /// 
    /// Http Get请求
    /// 
    /// 请求地址 
    /// 请求参数 
    /// 为防止重复请求实现HTTP幂等性(唯一ID)
    /// 
    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;
    }

    /// 
    /// Http Post请求
    /// 
    /// 请求地址
    /// 请求参数(json格式请求数据时contentType必须指定为application/json)
    /// 为防止重复请求实现HTTP幂等性(唯一ID)
    /// 
    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;
    }

    /// 
    /// 生成唯一标识符
    /// 
    /// 格式:N,D,B,P,X
    /// 
    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);
    }
技术图片

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

技术图片
 
技术图片

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


评论


亲,登录后才可以留言!