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;
    }
    调用:

    1. private void button1_Click(object sender, EventArgs e)
    2. {
    3. try
    4. {
    5. string sUrl3 = "http://localhost:10086/api/fun2";
    6. string sBody2 = JsonConvert.SerializeObject(new { p1 = "1", p2 = "2" });
    7. HttpHelper.HttpPost(sUrl3, sBody2);
    8. }
    9. catch (Exception ex)
    10. {}
    11. }

    HttpHelper.cs

    1. /// <summary>
    2. /// HttpPost (application/json)
    3. /// </summary>
    4. /// <param name="url"></param>
    5. /// <param name="body"></param>
    6. /// <param name="contentType"></param>
    7. /// <returns></returns>
    8. public static string HttpPost(string url, string body)
    9. {
    10. string responseContent = string.Empty;
    11. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    12. httpWebRequest.ContentType = "application/json";
    13. httpWebRequest.Method = "POST";
    14. httpWebRequest.Timeout = 200000000;
    15. //httpWebRequest.KeepAlive = true;
    16. httpWebRequest.MaximumResponseHeadersLength = 40000;
    17. byte[] btBodys = Encoding.UTF8.GetBytes(body);
    18. httpWebRequest.ContentLength = btBodys.Length;
    19. using (Stream writeStream = httpWebRequest.GetRequestStream())
    20. {
    21. writeStream.Write(btBodys, 0, btBodys.Length);
    22. }
    23. using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
    24. {
    25. using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    26. {
    27. responseContent = streamReader.ReadToEnd();
    28. }
    29. }
    30. return responseContent;
    31. }


    2、传对象
    接口定义:
    [OperationContract]
    [WebInvoke(UriTemplate = “api/fun”, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = “POST”, BodyStyle = WebMessageBodyStyle.Bare)]
    string TestFun(TestModel data);

    1. public string TestFun(TestModel pars)
    2. {
    3. try
    4. {
    5. return pars.Test1 + pars.Test2;
    6. }
    7. catch (Exception ex)
    8. {}
    9. }

    调用:

    1. private void button1_Click(object sender, EventArgs e)
    2. {
    3. try
    4. {
    5. string sUrl = "http://localhost:10086/api/fun";
    6. TestModel model = new TestModel();
    7. model.Test1 = "1";
    8. model.Test2 = "2";
    9. string sBody = JsonConvert.SerializeObject(model);
    10. HttpHelper.HttpPost(sUrl, sBody);
    11. }
    12. catch (Exception ex)
    13. { }
    14. }