1. 程式人生 > >REST服務Post建立以及呼叫小例子

REST服務Post建立以及呼叫小例子

服務端介面程式碼

[OperationContract]
        [WebInvoke(UriTemplate = "TestAddData", Method = "POST")]
        [Description("測試新增")]
        string TestAddData();

介面實現類方法

public string TestAddData()
        {
            string postJson = string.Empty;
            try
            {
                if (!OperationContext.Current.RequestContext.RequestMessage.IsEmpty)
                {
                    using (var reader = OperationContext.Current.RequestContext.RequestMessage.GetReaderAtBodyContents())
                    {
                        if (reader.Read())
                        {
                            postJson = new string(Encoding.UTF8.GetChars(reader.ReadContentAsBase64()));
                        }
                    }
                }
            }
            catch (Exception)
            {
                postJson = string.Empty;
            }            return "測試新增成功:" + postJson;
        }

asp.net客戶端呼叫方法

private string PostTest()
    {
        WebRequest req = WebRequest.Create(new Uri("服務地址"));
        req.Method = "POST";
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes("引數值");
        req.ContentType = "applicationson";
        req.ContentLength = bytes.Length;
        string str = string.Empty;
        using (Stream postStream = req.GetRequestStream())
        {
            postStream.Write(bytes, 0, bytes.Length);
        }
        using (WebResponse hwr = req.GetResponse())
        {
            using (StreamReader st = new StreamReader(hwr.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                str = HttpUtility.UrlDecode(st.ReadToEnd());
            }
        }
        if (!string.IsNullOrEmpty(str))
            return str;
        else
            return null;
    }