Zeeshan
Zeeshan

Reputation: 3024

Get expected Action Parameter type in OnActionExecuting

Question: Is it possible to know the type of parameter that is expected by the action being called? For example, I have some action as:

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

and TestCustomAttr is defined as:

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

So when the call is made to TestAction, here, inside OnActionExecuting, i want to know the type expected by the TestAction method. (e.g: in this case, there are 2 expected parameters. one is of type int and other one is of type string.

Actual Purpose: Actually i need to make changes to the values of QueryString. I'm already able to get the querystring values (through HttpContext.Current.Request.QueryString), change it, and then manually add it to ActionParameters as filterContext.ActionParameters[key] = updatedValue;

Problem: Currently, i try to parse the value to int, if it is successfully parsed, i assume, it is an int, so I make the require change (eg value + 1), and then add it to action parameters, against its key.

 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'
 }

but i want to know the exact expected type. because string can be as "123", and it will be assumed to be int and added as integer parameter, causing null exception, for other parameter. (vice versa). Therefore i want to parse the updated value to exact expected type, and then add to action parameters, against its key. So, how can i do this? Is this even possible? May be Reflection can help someway?

important: I'm open to suggestions. If my approach is not good to achieve the actual purpose, or if there is a better way of doing it, please share ;)

Upvotes: 3

Views: 3981

Answers (1)

Fedri Qrueger
Fedri Qrueger

Reputation: 641

you can get the parameter from the 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
        }

    }
}

Upvotes: 6

Related Questions