服务端接口代码
[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;
}