Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 控制器属性的ASP.NET MVC强制参数_Asp.net Mvc_Controller - Fatal编程技术网

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

Asp.net mvc 控制器属性的ASP.NET MVC强制参数,asp.net-mvc,controller,Asp.net Mvc,Controller,有没有办法用强制参数创建ASP.NET MVC属性 [MyPersonalAttribut(MyMandatoryValue="....")] public ActionResult Index() { return View(); } 谢谢,简单的方法是为索引方法提供一个不可为空的参数 public ActionResult Index(int id) { return View(); } 将需要一个有效的int来导航到那里您可以尝试这样的方法 动作

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

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

    return View();
}

谢谢,

简单的方法是为索引方法提供一个不可为空的参数

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

将需要一个有效的int来导航到那里

您可以尝试这样的方法

动作过滤器

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");
}

通过在属性中只有一个接受一个参数的构造函数,可以很容易地做到这一点。像这样:

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();
}

我知道,但我想要一个attribute@Kris-我知道你为什么想要一个属性?是的,但它在运行时。我想在编译时使用。我不明白你所说的编译时间是什么意思?我将属性放在操作的顶部,如果强制参数不存在,我将收到一个编译错误。