3

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

[TestCustomAttr]
public ActionResult TestAction(int a, string b)
{
    ...

TestCustomAttr定义为:

public class TestCustomAttr : System.Web.Mvc.ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...

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

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

问题: 目前,我尝试将 value 解析为int,如果解析成功,我假设它是 an int,所以我进行了 require 更改(例如 value + 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'
 }

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

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

4

1 回答 1

6

您可以从 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
        }

    }
}
于 2015-01-28T10:36:14.267 回答