Why is this Post operation failing?

邮差的信 提交于 2019-12-12 06:47:57

问题


Based on this, for my Web API project, I'm using this code on the client:

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;
    }
}

I reach the breakpoint I set on this line of code:

var webResponse = (HttpWebResponse)webRequest.GetResponse();

...but when I F10 over it (or try to F11 into it), it fails with "The remote server returned an error (411) Length Required"

The length of what is required, Compilerobot?!?

This is my method in the server's Repository class:

public void Post(Department department)
{
    int maxId = departments.Max(d => d.Id);
    department.Id = maxId + 1;
    departments.Add(department);
}

The Controller code is:

public void Post(Department department)
{
    deptsRepository.Post(department);
}

My GET methods are working fine; POST is the next step, but I'm stubbing my toe so far.


回答1:


You're not posting anything yet.

When you do.. you need to supply the length of the content. Somewhat like this:

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


来源:https://stackoverflow.com/questions/20647667/why-is-this-post-operation-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!