【问题标题】:.net core Avoid repeating ModelState in controller/action.net core 避免在控制器/动作中重复 ModelState
【发布时间】:2018-05-23 09:20:17
【问题描述】:

我在一个 .net core 2.x 项目中工作。 我在每个操作中编写以下代码来验证我的模型状态。

        if (ModelState.IsValid)
        {
            // Do something
        }
        else
        {
            // Return Modelstate Error
        }

我想知道避免在每个操作中重复条件的最佳做法是什么。 我想在执行操作之前验证模型状态,如果模型状态无效,则返回相应的错误消息。

更新

注意。我的操作是简单的 Api 操作,我只想在 HttpContext Body 中以字符串数组的形式返回错误(在我的模型中)。

例如模型属性。

    [Required(ErrorMessage = "Fill the name Please !!!")]
    public string FirstName { get; set; }

行动的例子。

    [HttpPost]
    public void Create([FromBody]MyModel model)
    {
        if (ModelState.IsValid)
        {
            // Do something
        }
        else
        {
            // Return Modelstate Error
        }
    }

【问题讨论】:

标签: .net validation asp.net-core modelstate


【解决方案1】:

试试这样的想法

 public class ModelStateValidationFilter : ActionFilterAttribute
    {
        public string ErrorPage;

        public override void OnActionExecuting(ActionExecutingContext context)
        {


 if (!context.ModelState.IsValid)
        {
            //return error result
            List<string> list = (from modelState in context.ModelState.Values from error in modelState.Errors select error.ErrorMessage).ToList();
            context.Result = new BadRequestObjectResult(list);

            //or redirect to some result
            context.Result = new RedirectToRouteResult(ErrorPage);

            //or do whatever you need
        }

        base.OnActionExecuting(context);
    }
}

并像这样添加它

在控制器上

[ModelStateValidationFilter(ErrorPage = "somepage")]
    public class SomeController : Controller

行动

[ModelStateValidationFilter(ErrorPage = "somepage")]
public IActionResult SomeAction(somemodel model)

或通过启动添加到所有

【讨论】:

  • 感谢您的回复。我的操作是简单的 Api,没有 IActionResult,我只想在我的 HttpContext 中返回错误数组(在我的模型中描述)。我不想返回错误页面。
  • @Arashbahreini 你需要一个 api 的例子吗?或者这个例子足够了吗?
猜你喜欢
  • 2022-07-27
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多