有条件需要基于控制器在ASP.NET核心

问题描述 投票:1回答:1

我想编写条件要求,但条件取决于它被使用在控制器上。

我已经有自定义属性MyRequiredIfNot。我只是不知道如何获取有关IsValid方法控制信息。

例如:

public class MyController1 : Controller
{
    public ActionResult Method1(MyModel model)
    { 
      //Name is required !!!
    }
}

public class MyController2 : MyController1 
{
    public ActionResult SomeMethod(MyModel model)
    { 
       //Name is NOT required !!!
    }
}

public class MyModel
{
    [MyRequiredIfNot(MyController2)
    public string Name { get;set; }
}

和失踪的实现:

public class MyRequiredIfNotAttribute : ValidationAttribute
{
    public MyRequiredIfNotAttribute(Controller controller) { }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (/*came_from ?*/ is this.controller)          //Missing !!!!
            return ValidationResult.Success;
        else
            return base.IsValid(value, validationContext);
    }
}
c# asp.net-core asp.net-core-mvc model-binding
1个回答
2
投票

对于检索qazxsw POI,你可以尝试qazxsw POI。

请按照以下步骤进行:

  1. 注册Controller IActionContextAccessor
  2. IActionContextAccessor public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); //rest services }
  3. 用法 qazxsw POI
© www.soinside.com 2019 - 2024. All rights reserved.