简体   繁体   English

如何在AuthorizationHandler中获取POST请求参数

[英]How get POST request params in AuthorizationHandler

I'm implementing a Policy-based authorization in ASP.NET Core 2.2, but I can't access to POST request params in the Verification Handler. 我正在ASP.NET Core 2.2中实现基于策略的授权,但是无法访问Verification Handler中的POST请求参数。

I try doing something like this: 我尝试做这样的事情:

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

But when I access Request.Form give me this error: 但是当我访问Request.Form给我这个错误:

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

在此处输入图片说明 I try with GET params in Request.QueryString and work successfully. 我尝试在Request.QueryString中使用GET参数并成功工作。

What's the correct way of access to POST params? 访问POST参数的正确方法是什么? I missed some configuration? 我错过了一些配置吗?

You can get body like this : 你可以像这样得到身体:

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

If you want access to the context you should register IHttpContextAccessor in the start up class 如果要访问上下文,则应在启动类中注册IHttpContextAccessor

services.AddScoped<IHttpContextAccessor, HttpContextAccessor>();

Based on your screenshot, it seems you want to read key node from request json body, if so, you could try read body as json and then get the node value like 根据您的屏幕截图,似乎您想从请求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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM