“HttpRequest”不包含“EnableRewind”的定义

Muh*_*aaz 2 authorization asp.net-core

我正在尝试在我创建的自定义授权处理程序中使用 EnableRewind 方法,但收到错误“'HttpRequest' 不包含 'EnableRewind' 的定义”,我需要访问其中的正文,但如果我这样做代码中显示我在控制器中收到错误“输入不包含任何 JSON 令牌。期望输入以有效的 JSON 令牌开头,....”这是我的处理程序,我从启动文件注入了 IHttpContextAccessor

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;

    }
}
Run Code Online (Sandbox Code Playgroud)

Muh*_*aaz 5

最后我解决了这个问题,实际上问题是 ASP .NET Core 使用 \xe2\x80\x93Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameRequestStream \xe2\x80\x93 的特定流不可回滚(发现这篇文章非常有帮助http://www.palador.com/2017/05/24/logging-the-body-of-http-request-and-response-in-asp-net-core/)所以通过创建新流解决了这个问题并将其放置在 body 中,如下所示:

\n
            var body = reader.ReadToEndAsync().Result;\n            var request = Newtonsoft.Json.JsonConvert.DeserializeObject<PrivateProfileModel>(body);\n\n            using (var injectedRequestStream = new MemoryStream())\n            {\n                var bytesToWrite = System.Text.Encoding.UTF8.GetBytes(body);\n                injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);\n                injectedRequestStream.Seek(0, SeekOrigin.Begin);\n                _httpContextAccessor.HttpContext.Request.Body = injectedRequestStream;\n            }\n
Run Code Online (Sandbox Code Playgroud)\n