Why is this Post operation failing?

2019-08-23 06:32发布

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条回答
Anthone
2楼-- · 2019-08-23 07:03

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
查看更多
登录 后发表回答