Reputation: 171
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?
Upvotes: 2
Views: 2452
Reputation: 29976
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);
}
Upvotes: 3
Reputation: 140
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>();
Upvotes: 0