Im trying to transmit a string from client to ASP.NET MVC4 application.
But I can not receive the string, either it is null or the post method can not be found (404 error)
Client Code to transmit the string (Console Application):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:49032/api/test");
request.Credentials = new NetworkCredential("user", "pw");
request.Method = "POST";
string postData = "Short test...";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
Console.ReadLine();
ASP.NET Web Api Controller:
public class TestController : ApiController
{
[Authorize]
public String Post(byte[] value)
{
return value.Length.ToString();
}
}
In that case I'm able to call the "Post" method, but "value" is NULL
.
If I change the method signature to (string value) than it will never called.
Even "without" the [Authorize] setting it has the same strange behavior. -> So it has nothing to do with the user authentication.
Any ideas what I'm doing wrong? I'm grateful for any help.
Darrel is of course right on with his response. One thing to add is that the reason why attempting to bind to a body containing a single token like "hello".
is that it isn’t quite URL form encoded data. By adding “=” in front like this:
it becomes a URL form encoding of a single key value pair with an empty name and value of “hello”.
However, a better solution is to use application/json when uploading a string:
Using HttpClient you can do it as follows:
Henrik