代码之家  ›  专栏  ›  技术社区  ›  Janilson

Post请求处理作为查询字符串发送的内容,但当内容作为StringContent发送时,会导致404错误

  •  0
  • Janilson  · 技术社区  · 8 年前

    我已经在asp上设置了一个Web Api 2控制器。net来处理对localhost的简单post请求,仅用于测试目的。当我使用“ https://localhost:xxxx/api/test?content=teststring “控制器可以很好地处理POST请求,但是使用just时” https://localhost:xxxx/api/test “作为以teststring作为StringContent对象的uri,我得到一个404错误。以下是控制器代码:

    [RoutePrefix("api")]
    public class TestController : ApiController
    {
        [HttpPost]
        [Route("test")]
        public HttpResponseMessage PostTest(string content)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent(content + "\nHiAndBye");
            return response;
        }
    }
    

    以下是我在收到404错误时如何发送POST请求(从控制台应用程序):

    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("https://localhost:xxxxx");
    StringContent content = new StringContent("teststring");
    HttpResponseMessage response = httpClient.PostAsync("/api/test", content).Result;
    

    如何修复404错误?

    2 回复  |  直到 8 年前
        1
  •  0
  •   Jim W    8 年前

    如果Johnny在评论中的回答不够明确,您需要做的是将方法签名更改为

    public HttpResponseMessage PostTest([FromBody] string content)
    

    它迫使 content 要从请求正文而不是URL读取的参数。你可以在这里阅读更多内容 https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

        2
  •  0
  •   Janilson    8 年前

    我发现解决这个问题的方法是让PostTest控制器没有参数,然后使用这个。要求所容纳之物ReadAsStringAsync()。结果获取请求的正文,因此控制器现在如下所示:

    public HttpResponseMessage PostTest()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent(this.Request.Content.ReadAsStringAsync().Result + "\nHiAndBye");
            return response;
        }
    
    推荐文章