asp.net-mvc-2 - 如何在 ASP.NET MVC 中将动态变量传递给 Action Filter

标签 asp.net-mvc-2 action-filter dynamic-variables custom-action-filter

我想使用变量将动态值传递给我的操作过滤器。我以为会是这样的:

[MessageActionFilter(message = "User is updating item: " & id)]
public ActionResult doSomething(int id)
{
    // do something
}

但是,似乎参数必须是常量值。因此,我的问题是如何将变量获取到我的操作过滤器?

最佳答案

您可以使用 ActionExecutingContext.ActionParameters 获取 OnActionExecuting 中的参数值属性(property)。

这只是一个伪代码,但是例如您可以检索名为 id 的参数

public class MessageActionFilter: ActionFilterAttribute 
{     
    public override void OnActionExecuting(ActionExecutingContext filterContext)     
    {         
        var response = filterContext.HttpContext.Response;                   

        var parameterValue = filterContext.ActionParameters.SingleOrDefault(p => p.Key == "id");

        // check if not null before writing a message

        response.Write(this.Message + parameterValue); // prints "User is updating item: <idvalue>"
    }

    public string Message {get; set;}
} 

告诉我是否有帮助。

关于asp.net-mvc-2 - 如何在 ASP.NET MVC 中将动态变量传递给 Action Filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8536556/

相关文章:

java - Java中如何拥有动态数据类型的变量?

c# - C#中的动态变量?

网站内的asp.net mvc 2 web 应用程序?

html - MVC2 : Impossible to change the name with TextBoxFor?

asp.net - 如何从 ASP.NET MVC 中的表单例份验证中拦截 401?

asp.net-mvc - 如何使用 Autofac 将 "bind"属性添加到操作过滤器?

asp.net-mvc - MVC5 读取配置值而不使用 System.Web

asp.net-mvc-2 - ASP.NET MVC 2 中使用无模型 View 进行客户端验证

asp.net-mvc - 我们什么时候应该实现自定义 MVC ActionFilter?

javascript - 变量运算符可能吗?