【WCF Restful】Post传参示范

1、传多个参数

接口定义:(ResponseFormat与RequestFormat分别将相应参数序列化、请求参数反序列化)

[OperationContract]
[WebInvoke(UriTemplate = "api/fun2", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
 string TestFun2(string p1,string p2);

实现:

public string TestFun2(string p1, string p2)
{
   return p1+p2; 
}

调用:

private void button1_Click(object sender, EventArgs e)
{
   try
   {
      string sUrl3 = "http://localhost:10086/api/fun2";
      string sBody2 = JsonConvert.SerializeObject(new { p1 = "1", p2 = "2" });

      HttpHelper.HttpPost(sUrl3, sBody2);
   }
   catch (Exception ex)
   {}
}

HttpHelper.cs

/// <summary>
        /// HttpPost (application/json)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string body)
        {
            string responseContent = string.Empty;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 200000000;
            //httpWebRequest.KeepAlive = true;
            httpWebRequest.MaximumResponseHeadersLength = 40000;

            byte[] btBodys = Encoding.UTF8.GetBytes(body);
            httpWebRequest.ContentLength = btBodys.Length;

            using (Stream writeStream = httpWebRequest.GetRequestStream())
            {
                writeStream.Write(btBodys, 0, btBodys.Length);
            }

            using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                {
                    responseContent = streamReader.ReadToEnd();
                }
            }

            return responseContent;
        }
HttpHelper

 

2、传对象

 接口定义:

[OperationContract]
[WebInvoke(UriTemplate = "api/fun", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
 string TestFun(TestModel data);

实现:

 public string TestFun(TestModel pars)
 {
    try
    {
       return pars.Test1 + pars.Test2;
    }
    catch (Exception ex)
    {}
}

调用:

private void button1_Click(object sender, EventArgs e)
{
   try
   {
      string sUrl = "http://localhost:10086/api/fun";
                
      TestModel model = new TestModel();
      model.Test1 = "1";
      model.Test2 = "2";

      string sBody = JsonConvert.SerializeObject(model);
               
      HttpHelper.HttpPost(sUrl, sBody);
   }
   catch (Exception ex)
   { }
}
posted @ 2020-01-15 14:44  沙奇码丶  阅读(...)  评论(...编辑  收藏