Why is the body of a Web API request read once?

前端 未结 2 1434
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 15:20

My goal is to authenticate Web API requests using a AuthorizationFilter or DelegatingHandler. I want to look for the client id and authentication token in a few places, incl

相关标签:
2条回答
  • 2020-12-08 15:43

    The answer you pointed to is not entirely accurate.

    You can always read as string (ReadAsStringAsync)or as byte[] (ReadAsByteArrayAsync) as they buffer the request internally.

    For example the dummy handler below:

    public class MyHandler : DelegatingHandler
    {
        protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var body = await request.Content.ReadAsStringAsync();
            //deserialize from string i.e. using JSON.NET
    
            return base.SendAsync(request, cancellationToken);
        }
    }
    

    Same applies to byte[]:

    public class MessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var requestMessage = await request.Content.ReadAsByteArrayAsync();
            //do something with requestMessage - but you will have to deserialize from byte[]
    
            return base.SendAsync(request, cancellationToken);
        }
    }
    

    Each will not cause the posted content to be null when it reaches the controller.

    0 讨论(0)
  • 2020-12-08 15:59

    I'd put the clientId and the authentication key in the header rather than content.

    In which way, you can read them as many times as you like!

    0 讨论(0)
提交回复
热议问题