简体   繁体   English

在ActionFilterAttribute中从.NET Core Web API上的请求正文获取JSON数据

[英]Get JSON data from request body on .NET Core Web API within ActionFilterAttribute

I am writing a custom ActionFilterAttribute in order to handle some business logic before the request hits the action in .Net Core Web API. 我正在编写一个自定义ActionFilterAttribute,以便在请求击中.Net Core Web API中的操作之前处理一些业务逻辑。 (Core v1.1) The handler is being successfully hit by OnActionExecuting, but I am not able to extract its data sent in JSON format that is coming from the request body. (Core v1.1)处理程序已成功通过OnActionExecuting命中,但我无法提取其以请求主体的JSON格式发送的数据。

I have tried in few ways, like reading the ActionExecutingContext stream body (which comes empty), accesing the Form property (but as it is json, it does not work), and some other solutions but no luck on that. 我已经尝试了几种方法,例如读取ActionExecutingContext流主体(该实体为空),访问Form属性(但由于它是json,所以不起作用),以及其他一些解决方案,但是没有运气。

This is the code for my ActionFilter, which is empty, since the issue here is basically the need to extract its data, so further code would be irrelevant. 这是我的ActionFilter的代码,为空,因为这里的问题基本上是需要提取其数据,所以其他代码将是无关紧要的。

public class AccountRestrictionAttribute : ActionFilterAttribute
{
     public override async void OnActionExecuting(ActionExecutingContext context)
     {      
     }
}

Answer credit goes to rynowak, I found it here https://github.com/aspnet/Mvc/issues/5260 答案归功于rynowak,我在这里找到了它https://github.com/aspnet/Mvc/issues/5260

ModelBinding runs before action filters so if you have form data or a [FromBody] parameter, we've already read it. ModelBinding在动作过滤器之前运行,因此,如果您有表单数据或[FromBody]参数,我们已经阅读了。

Yes, if you're inside an action filter then context.ActionArguments will contain all of the model objects we created. 是的,如果您位于动作过滤器中,那么context.ActionArguments将包含我们创建的所有模型对象。 So if you have: 因此,如果您有:

public IActionResult Edit(int id, [FromBody] Widget widget) { }

Then context.ActionArguments["widget"] will return the Widget object. 然后context.ActionArguments [“ widget”]将返回Widget对象。 If you're trying to do this in a generic way, look at context.ActionDescriptor.Parameters - this will contain all of the parameter definitions and metadata. 如果您尝试以通用方式执行此操作,请查看context.ActionDescriptor.Parameters-这将包含所有参数定义和元数据。

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

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