Read HttpContent in WebApi controller

前端 未结 3 678
执念已碎
执念已碎 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:19

    Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.

    If you still want to have the model as a parameter in the method, you can create a DelegatingHandler to buffer the content.

    internal sealed class BufferizingHandler : DelegatingHandler
    {
        protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            await request.Content.LoadIntoBufferAsync();
            var result = await base.SendAsync(request, cancellationToken);
            return result;
        }
    }
    

    And add it to the global message handlers:

    configuration.MessageHandlers.Add(new BufferizingHandler());
    

    This solution is based on the answer by Darrel Miller.

    This way all the requests will be buffered.

提交回复
热议问题