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

前端 未结 7 1594
有刺的猬
有刺的猬 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:44

    Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.

     public class TextController : ApiController
        {
            public HttpResponseMessage Post(HttpRequestMessage request) {
    
                var someText = request.Content.ReadAsStringAsync().Result;
                return new HttpResponseMessage() {Content = new StringContent(someText)};
    
            }
    
        }
    

    This controller will handle a HTTP request, read a string out of the payload and return that string back.

    You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.

        [Fact]
        public void PostAString()
        {
    
            var client = new HttpClient();
    
            var content = new StringContent("Some text");
            var response = client.PostAsync("http://oak:9999/api/text", content).Result;
    
            Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);
    
        }
    
    0 讨论(0)
提交回复
热议问题