基于this,对于我的Web API项目,我在客户端上使用此代码:
private void AddDepartment()
{
int onAccountOfWally = 42;
string moniker = "Billy Bob";
Cursor.Current = Cursors.WaitCursor;
try
{
string uri = String.Format("http://platypi:28642/api/Departments/{0}/{1}", onAccountOfWally, moniker);
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
MessageBox.Show(string.Format("Failed: {0}", webResponse.StatusCode.ToString()));
}
}
finally
{
Cursor.Current = Cursors.Default;
}
}
我到达了我在这行代码上设置的断点:
var webResponse = (HttpWebResponse)webRequest.GetResponse();
...但是当我F10通过它(或尝试到F11进入它)时,它失败并显示“远程服务器返回错误(411)所需长度 “
需要什么的长度,Compilerobot?!?
这是我在服务器的Repository类中的方法:
public void Post(Department department)
{
int maxId = departments.Max(d => d.Id);
department.Id = maxId + 1;
departments.Add(department);
}
Controller代码是:
public void Post(Department department)
{
deptsRepository.Post(department);
}
我的GET方法运行正常; POST是下一步,但到目前为止,我的脚趾已经短了。
答案 0 :(得分:1)
你还没有发布任何内容。
当你这样做时......你需要提供内容的长度。有点像这样:
byte[] yourData = new byte[1024]; // example only .. this will be your data
webRequest.ContentLength = yourData.Length; // set Content Length
var requestStream = webRequest.GetRequestStream(); // get stream for request
requestStream.Write(yourData, 0, yourData.Length); // write to request stream