0
基于this,为我的Web API项目,我在客户端使用此代码:为什么Post操作失败?
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?!?
这是我在服务器的存储库类方法:
public void Post(Department department)
{
int maxId = departments.Max(d => d.Id);
department.Id = maxId + 1;
departments.Add(department);
}
的控制器代码:
public void Post(Department department)
{
deptsRepository.Post(department);
}
我GET方法做工精细; POST是下一个步骤,但我已经把脚趾钉到了目前为止。
根据这里的答案:http://stackoverflow.com/questions/20646715/how-can-i-call-a-web-api-post-method,我需要这条线代码: var webResponse =(HttpWebResponse)webRequest.GetResponse(); 在这种情况下我真的需要一个RequestStream(发布数据)吗? –
是的。 'GetResponse'用于从您的请求中检索_response_。 'GetRequestStream'获取用于为请求写入数据的'Stream'。如果你想发送一些请求,你需要写信给它。 –