POST string to ASP.NET Web Api application - returns null

前端 未结 7 1623
有刺的猬
有刺的猬 2020-11-28 08:05

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

7条回答
  •  自闭症患者
    2020-11-28 08:41

    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:

    =hello
    

    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:

    POST /api/sample HTTP/1.1
    Content-Type: application/json; charset=utf-8
    Host: host:8080
    Content-Length: 7
    
    "Hello"
    

    Using HttpClient you can do it as follows:

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.PostAsJsonAsync(_baseAddress + "api/json", "Hello");
    string result = await response.Content.ReadAsStringAsync();
    Console.WriteLine(result);
    

    Henrik

提交回复
热议问题