在OnActionExecuting中获取预期的Action参数类型

Zee*_*han 2 c# custom-attributes query-string onactionexecuting asp.net-mvc-4

问题: 是否可以知道被调用动作所期望的参数类型?例如,我有一些action:

[TestCustomAttr]
public ActionResult TestAction(int a, string b)
{
    ...
Run Code Online (Sandbox Code Playgroud)

TestCustomAttr定义为:

public class TestCustomAttr : System.Web.Mvc.ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...
Run Code Online (Sandbox Code Playgroud)

因此,当调用TestAction此处内部时OnActionExecuting,我想知道该TestAction方法所期望的类型.(例如:在这种情况下,有2个预期参数.一个是类型int,另一个是类型string.

实际目的: 实际上我需要更改值QueryString.我已经能够获取查询字符串值(通过HttpContext.Current.Request.QueryString),更改它,然后手动将其添加ActionParametersfilterContext.ActionParameters[key] = updatedValue;

问题: 目前,我尝试将值解析为int,如果它被成功解析,我认为它是一个int,所以我进行需求更改(例如值+ 1),然后将其添加到操作参数,对应其键.

 qsValue = HttpContext.Current.Request.QueryString[someKey].ToString();

 if(Int32.TryParse(qsValue, out intValue))
 {
     //here i assume, expected parameter is of type `int`
 }
 else
 {
     //here i assume, expected parameter is of type 'string'
 }
Run Code Online (Sandbox Code Playgroud)

但我想知道确切的预期类型.因为string可以是as "123",并且它将被假定为int并作为整数参数添加,从而导致其他参数的null异常.(反之亦然).因此,我想将更新后的值解析为精确的预期类型,然后根据其键添加到操作参数.那么,我该怎么做呢?这甚至可能吗?可能会Reflection有所帮助吗?

重要的是:我愿意接受建议.如果我的方法不能达到实际目的,或者有更好的方法,请分享;)

小智 5

您可以从ActionDescriptor获取参数.

public class TestCustomAttr : System.Web.Mvc.ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var ActionInfo = filterContext.ActionDescriptor;
        var pars = ActionInfo.GetParameters();
        foreach (var p in pars)
        {

           var type = p.ParameterType; //get type expected
        }

    }
}
Run Code Online (Sandbox Code Playgroud)