简体   繁体   English

自定义 MVC controller 动作属性来检查和操作动作输入

[英]Custom MVC controller action attribute to check and manipulate action inputs

Good evening晚上好

I am trying to refine our controllers validation;我正在尝试改进我们的控制器验证; some of my fellow developers were forced to use [ValidateInput(false)] on some controllers, but now we need a finer check on the parameters they accept.我的一些开发人员同事被迫在某些控制器上使用 [ValidateInput(false)],但现在我们需要对他们接受的参数进行更精细的检查。

What I am trying to achieve is writing a custom validation attribute to use instead of [ValidateInput(false)] to check data in input, and if possible alter it.我想要实现的是编写一个自定义验证属性来代替 [ValidateInput(false)] 来检查输入中的数据,并在可能的情况下更改它。 So a controller like:所以像 controller 这样的:

[HttpPost]
[ValidateInput(false)]
public JsonResult SetData(long id, string text1, string text2)

should be treated this way应该这样对待

[HttpPost]
[MyCustomAttribute]
public JsonResult SetData(long id, string text1, string text2)

and I need in my attribute code to check all incoming parameters one by one and perform specific checks and possibly transformations based on their type:我需要在我的属性代码中一一检查所有传入的参数,并根据它们的类型执行特定的检查和可能的转换:

MyCustomAttribute(context) {

   //Extract somehow a list of parameters pars from the context

   for (var i in pars) {
      if (pars[i] is string) {
         //Alter strings
         ((string)pars[i]).Replace("a", "x"); //Just an example
      }
      if (pars[i] is long) {
         //Alter numbers
         if ((long)pars[i] < 0) pars[i] = 0; //Just an example
      }
   }
}

The alterations inside the attribute logic needs to be permanent so that controller's logic does not need to care about parameters outside the domain of allowed values.属性逻辑内部的更改需要是永久性的,以便控制器的逻辑不需要关心允许值域之外的参数。 Is this possible?这可能吗? I am sorry for my poor skills in attributes, and if my question should result trivial or absurd.我很抱歉我的属性技能很差,如果我的问题变得琐碎或荒谬。

I managed to solve this problem.我设法解决了这个问题。 It can be created an ActionFilterAttribute where inside the overridden function OnActionExecuting it can be analyzed and altered the member ActionParameters of the ActionExecutingContext passed to the function, as follows:可以创建一个 ActionFilterAttribute,其中在覆盖的 function OnActionExecuting 内部可以分析和更改传递给 function 的 ActionExecutingContext 的成员 ActionParameters,如下所示:

public class MyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Logic here
        var myField = filterContext.ActionParameters["myField"];
    }
}

ActionExecutingContext.ActionParameters can be cycled to perform type-based check/manupulation in all its members, or punctually in one of them if its name is known. ActionExecutingContext.ActionParameters 可以循环以在其所有成员中执行基于类型的检查/操作,或者如果其名称已知,则可以准时在其中之一中执行。

Thanks for your attention.感谢您的关注。

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

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