我的服务合同
[ServiceContract]
public interface ITsdxService
{
[OperationContract]
[WebGet(UriTemplate="/GetTestCostCentre")]
CostCentre GetTestCostCentre();
[OperationContract]
[WebInvoke(UriTemplate="/SetCostCentre", Method="POST")]
string SetCostCentre(CostCentre cc);
}
public class TsdxService : ITsdxService
{
public CostCentre GetTestCostCentre()
{
CostCentre cc = new CostCentre();
cc.Code = "Test";
cc.Name = "Test Cost Centre";
cc.Description = new byte[] { 12, 34, 89, 240, 66, 87, 189 };
cc.SAPStatus = "Existent";
cc.SAPSiteFolder = "Folder1";
return cc;
}
public string SetCostCentre(CostCentre cc)
{
return cc.Code;
}
}
然后我启动此服务并尝试从不同的应用程序使用它:
Uri requestUri = new Uri(textBox1.Text + "/tsdx/GetTestCostCentre");
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
XElement root;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
root = XElement.Parse(reader.ReadToEnd());
textBox2.Text = root.ToString();
}
一切正常,我正在获取 xml 文档。但是当我尝试向该服务发送 POST 请求时遇到了问题:
Uri requestUri = new Uri(textBox1.Text + "/tsdx/SetCostCentre");
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
byte[] bytes = Encoding.UTF8.GetBytes(textBox2.Text);
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream dataStream = request.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
textBox2.Text = reader.ReadToEnd();
}
异常:远程服务器返回错误:(400)错误请求。
我做错了什么?