RESTサービスPostの作成および呼び出しの例

1920 ワード

サービス側インタフェースコード
[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;
    }