passing action method parameter to ActionFilterAttribute in asp.net mvc

我只是一个虾纸丫 提交于 2019-11-30 01:58:12

Building on the answer from @Pankaj and comments from @csetzkorn:

You pass the name of the parameter as a string then check the filterContext

public class NewAuthoriseAttribute : ActionFilterAttribute
{
    public string IdParamName { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionParameters.ContainsKey(IdParamName))
        {
            var id = filterContext.ActionParameters[IdParamName] as Int32?;
        }
    }
}

[NewAuthorizeAttribute(IdParamName = "fooId")]
public ActionResult Index(int fooId)
{ ... }

Edit

I am assuming that you are looking to make the Alias of Parameter name. This is giving you the flexibility to have multiple Alias of your paramater Name.

ActionParameterAlias.ParameterAlias Overloads

If so, you can give alias like below.

[ParameterAlias("Original_Parameter_Name", 
                 "New_Parameter_Name")]
[ParameterAlias("Original_Parameter_Name", 
                 "New_Parameter_Name1")]
[ParameterAlias("Original_Parameter_Name", 
                 "New_Parameter_Name2")]
[ParameterAlias("Original_Parameter_Name", 
                 "New_Parameter_Name3")]

public ActionResult ActionMethod(Model ParameterValue) { return View(ParameterValue); }


Original Post

Try this one.

Attribute

public class NewAuthoriseAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionParameters.ContainsKey("id"))
        {
            var id = filterContext.ActionParameters["id"] as Int32?;
        }
    }
}

Action Method

Make sure to set the Parameter type nullable to avoid RunTime Crash.

[NewAuthoriseAttribute]
public ActionResult Index(Int32? id)
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!