控制器属性的ASP.NET MVC强制性参数

控制器属性的ASP.NET MVC强制性参数

问题描述:

有没有办法用强制参数创建ASP.NET MVC属性?控制器属性的ASP.NET MVC强制性参数

[MyPersonalAttribut(MyMandatoryValue="....")] 
public ActionResult Index() 
{ 

    return View(); 
} 

感谢,

最简单的方法是有index方法

public ActionResult Index(int id) 
    { 
    return View(); 
    } 

不可为空的参数需要一个有效的int导航有

+0

我知道,但我想一个属性 – 2012-07-11 06:00:30

+0

@克里斯-I *瓦你*你想要一个属性? – 2012-07-11 13:53:45

你可以试一下像这样,

动作过滤器

public class MandatoryAttribute: FilterAttribute, IActionFilter 
{ 
    private readonly string _requiredField; 

    public MandatoryAttribute(string requiredField) 
    { 
     _requiredField = requiredField; 
    } 

    public void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
    } 

    public void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     var val = filterContext.Controller.ValueProvider.GetValue(_requiredField); 

     if (val == null || string.IsNullOrEmpty(val.AttemptedValue)) 
      throw new Exception(string.Format("{0} is missing"), 
          _requiredField); 
    } 
} 

行动

[Mandatory("param")] 
public ActionResult MyTest() 
{ 
    return Content("OK"); 
} 
+0

是的,但它在运行时。我想在汇编时间。 – 2012-07-11 16:40:35

+0

我不明白你编译的时间是什么意思? – VJAI 2012-07-11 16:44:16

+0

如果强制性参数不存在,我将该属性放在操作的顶部,我收到一个编译错误。 – 2012-07-13 08:28:03

您可以轻松地做到这一点的只有一个在它有一个参数的构造属性。就像这样:

public class MyPersonalAttribute : Attribute 
{ 
    public object MyMandatoryValue { get; private set; } 

    // The only constructor in the class that takes one argument... 
    public MyPersonalAttribute(object value) 
    { 
     this.MyMandatoryValue = value; 
    } 
} 

然后,如果你会得到一个收到一个编译错误,如果你没有采用像下面的属性时的说法:

这将工作:

[MyPersonalAttribute("some value")] 
public ActionResult Index() 
{ 
    return View(); 
} 

这会给你一个编译错误:

[MyPersonalAttribute()] 
public ActionResult Index() 
{ 
    return View(); 
}