【WCF Restful】Post傳參示範

一、傳多個參數json

接口定義:(ResponseFormat與RequestFormat分別將相應參數序列化、請求參數反序列化)api

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

實現:app

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

調用:ide

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.csurl

/// <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

 

二、傳對象spa

 接口定義:code

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

實現:orm

 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)
   { }
}
相關文章
相關標籤/搜索