How to capture the body value (Stream) of a request without deleting it?

Asked

Viewed 275 times

0

I’m trying to capture the body of a request in an authorization class (Authorizationhandler), but because this body is a Stream, after reading its contents the post request that comes next can not be executed because the stream has already been read and its content no longer exists.

I’m using the following code:

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, Autorizacao requirement)
{
    var routeValues = context.Resource as AuthorizationFilterContext;
    if (routeValues != null)
    {
        var obj = StreamToObject(routeValues.HttpContext.Request.Body);
        context.Succeed(requirement);
    }
    return Task.FromResult(0);
}

private Object StreamToObject(Stream stream)
{
    try
    {
        string content;
        using (var reader = new StreamReader(stream))
        content = reader.ReadToEnd();
        return Newtonsoft.Json.JsonConvert.DeserializeObject(content);
    }
    catch (Exception e)
    {
        throw e;
    }
}

I know this is happening because after reading the stream your content is being discarded, but I would like to know what I can do to get around this problem ?

  • what comes in that stream?

  • @miltoncamara A json in string format that transforms into an object.

  • you send in the same request a form and a json? Did I get it right?

  • I send only one json on the POST body.

  • This project is a webapi?

  • Yes, I changed the above code to make it clearer. This is part of authenticating an api

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.