Read HttpContent in WebApi controller

前端 未结 3 688
执念已碎
执念已碎 2020-12-02 11:49

How can I read the contents on the PUT request in MVC webApi controller action.

[HttpPut]
public HttpResponseMessage Put(int accountId, Contact contact)
{
           


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 12:29

    By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.

    The first read in your case is being done when Web API is binding your model, after that the Request.Content will not return anything.

    You can remove the contact from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):

    [HttpPut]
    public HttpResponseMessage Put(int accountId)
    {
        HttpContent requestContent = Request.Content;
        string jsonContent = requestContent.ReadAsStringAsync().Result;
        CONTACT contact = JsonConvert.DeserializeObject(jsonContent);
        ...
    }
    

    That should do the trick (assuming that accountId is URL parameter so it will not be treated as content read).

提交回复
热议问题