将动作方法参数传递给ASP.NET MVC中的ActionFilterAttribute [英] passing action method parameter to ActionFilterAttribute in asp.net mvc

查看:208
本文介绍了将动作方法参数传递给ASP.NET MVC中的ActionFilterAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用filterContext来达到目的.但是,如果以不同的方式命名操作方法参数,则这种方法不是很灵活.这应该起作用:

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:

[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?

推荐答案

以@Pankaj的答案和@csetzkorn的评论为基础:

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

您将参数名称作为字符串传递,然后检查filterContext

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

这篇关于将动作方法参数传递给ASP.NET MVC中的ActionFilterAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆