C# 为什么这次手术失败了?

C# 为什么这次手术失败了?,c#,asp.net-web-api,controller,repository,asp.net-web-api-routing,C#,Asp.net Web Api,Controller,Repository,Asp.net Web Api Routing,基于,对于我的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/Departm

基于,对于我的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)所需的长度”

所需的长度是多少,编译器机器人

这是我在服务器的存储库类中的方法:

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方法运行良好;发帖是下一步,但到目前为止我还没有发帖。

你还没有发帖

当你这样做的时候。。您需要提供内容的长度。有点像这样:

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

根据这里的答案:,我需要这行代码:var webResponse=(HttpWebResponse)webRequest.GetResponse();在这种情况下,我真的需要RequestStream吗(发布数据)?是的
GetResponse
用于从请求中检索响应
GetRequestStream
获取用于为请求写入数据的
流。如果您想随请求一起发送内容。。你需要给它写信。