'HttpRequest' does not contain a definition for 'EnableRewind'

Viewed 3733

I am trying to use the EnableRewind method in a custom authorization handler which I have created but i am getting the error "'HttpRequest' does not contain a definition for 'EnableRewind'" I need to access body in it but if I do it as shown in code I get the error in the controller "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token,...." this is my handler i have injected IHttpContextAccessor from the startup file

public class ForPrivateProfileBodyMustOwnRecordOrShouldBeInAdminRoleHandler : AuthorizationHandler<ForPrivateProfileBodyMustOwnRecordOrShouldBeInAdminRole>
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public ForPrivateProfileBodyMustOwnRecordOrShouldBeInAdminRoleHandler(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, 
          ForPrivateProfileBodyMustOwnRecordOrShouldBeInAdminRole requirement)
    {
       var reader = new System.IO.StreamReader(_httpContextAccessor.HttpContext.Request.Body);

        
        
        var body = reader.ReadToEndAsync().Result;
        //this line is producing error
        var req = _httpContextAccessor.HttpContext.Request.EnableRewind();
        var request = Newtonsoft.Json.JsonConvert.DeserializeObject<PrivateProfileModel>(body);
        var ownerId = context.User.Claims.FirstOrDefault(c => c.Type == "sub")?.Value;
        if (request.UserId.ToString() != ownerId && !context.User.IsInRole("Admin"))
        {
            context.Fail();
            return Task.CompletedTask;
        }
        //all checks pass
        //_httpContextAccessor.HttpContext.Request.Body.Seek(0, System.IO.SeekOrigin.Begin);
        context.Succeed(requirement);
        return Task.CompletedTask;

    }
}
1 Answers

finally i have resolved this issue actually the issue was the particular stream that ASP .NET Core uses –Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameRequestStream – is not rewindable (found this article quite helpful http://www.palador.com/2017/05/24/logging-the-body-of-http-request-and-response-in-asp-net-core/) so solved it by creating new stream and placing it in body like this :

            var body = reader.ReadToEndAsync().Result;
            var request = Newtonsoft.Json.JsonConvert.DeserializeObject<PrivateProfileModel>(body);

            using (var injectedRequestStream = new MemoryStream())
            {
                var bytesToWrite = System.Text.Encoding.UTF8.GetBytes(body);
                injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
                injectedRequestStream.Seek(0, SeekOrigin.Begin);
                _httpContextAccessor.HttpContext.Request.Body = injectedRequestStream;
            }
Related