简体   繁体   中英

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.

I try doing something like this:

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

But when I access Request.Form give me this error:

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

在此处输入图片说明 I try with GET params in Request.QueryString and work successfully.

What's the correct way of access to POST params? 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

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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