【问题标题】:How get POST request params in AuthorizationHandler如何在 AuthorizationHandler 中获取 POST 请求参数
【发布时间】:2019-08-21 14:12:59
【问题描述】:

我正在 ASP.NET Core 2.2 中实现基于策略的授权,但无法访问验证处理程序中的 POST 请求参数。

我尝试做这样的事情:

mvcContext.HttpContext.Request.Form["key"]

但是当我访问 Request.Form 时给我这个错误:

'mvcContext.HttpContext.Request.Form' threw an exception of type 'System.InvalidOperationException'

我尝试使用 Request.QueryString 中的 GET 参数并成功运行。

访问 POST 参数的正确方法是什么?我错过了一些配置?

【问题讨论】:

    标签: c# asp.net-core .net-core


    【解决方案1】:

    根据您的屏幕截图,您似乎想从请求 json 正文中读取关键节点,如果是这样,您可以尝试将正文读取为 json,然后获取节点值,如

    if (context.Resource is AuthorizationFilterContext mvcContext)
    {
        var request = mvcContext.HttpContext.Request;
        request.EnableRewind();
        var reader = new StreamReader(request.Body);
        string body = reader.ReadToEnd();
        var model = JsonConvert.DeserializeObject(body, mvcContext.ActionDescriptor.Parameters.FirstOrDefault().ParameterType);
        JToken key;
        JObject.Parse(body).TryGetValue("key", StringComparison.InvariantCultureIgnoreCase, out key);
    
        request.Body.Seek(0, SeekOrigin.Begin);
    }
    

    【讨论】:

      【解决方案2】:

      你可以得到这样的身体:

      [HttpPost]
      public string SampleMethod([FromBody] YourModel model)
      {
          //access to the model here
      }
      

      如果你想访问上下文,你应该在启动类中注册 IHttpContextAccessor

      services.AddScoped<IHttpContextAccessor, HttpContextAccessor>();
      

      【讨论】:

        猜你喜欢
        • 2021-01-12
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-08
        • 1970-01-01
        • 2019-06-14
        • 1970-01-01
        相关资源
        最近更新 更多