asp.net-mvc 将动作方法参数传递给 asp.net mvc 中的 ActionFilterAttribute
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15530779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing action method parameter to ActionFilterAttribute in asp.net mvc
提问by cs0815
I know that I can use the filterContext to get to it. However, this is not very flexible if the action method parameter is named differently. This should work:
我知道我可以使用 filterContext 来获得它。但是,如果操作方法参数的名称不同,这不是很灵活。这应该有效:
[HttpGet]
[NewAuthoriseAttribute(SomeId = id)]
public ActionResult Index(int id)
{
...
public class NewActionFilterAttribute : ActionFilterAttribute
{
public int SomeId { get; set; }
...
but it does not (it does not even compile). Any ideas?
但它没有(它甚至不编译)。有任何想法吗?
回答by Jasen
Building on the answer from @Pankaj and comments from @csetzkorn:
基于@Pankaj 的回答和@csetzkorn 的评论:
You pass the name of the parameter as a string then check the filterContext
您将参数的名称作为字符串传递,然后检查 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)
{ ... }
回答by cs0815
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
ActionParameterAlias.ParameterAlias 重载


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)
{
}

