如何避免在每个PostBack上调用ModelState.IsValid? [英] How to avoid calling ModelState.IsValid on every PostBack?

查看:77
本文介绍了如何避免在每个PostBack上调用ModelState.IsValid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎总是想检查回发时是否调用了ModelSate.IsValid.而且必须在每次发回邮件的开头进行检查都违反了DRY原则,有没有办法自动对其进行检查?

I pretty much always want to check if ModelSate.IsValid is called when I do a postback. And having to check at the start of every post back violates the DRY principle, is there a way to have it checked automatically?

示例:

[HttpPost("RegisterUser")]
[AllowAnonymous]
public async Task<IActionResult> RegisterUser([FromBody] UserRegisterViewModel vmodel)
{
    if(!ModelState.IsValid)          // This code is repeated at every postback
        return ModelInvalidAction(); // Is there a way to avoid having to write it down?

    // do other things

    return StatusCode(201);
}

推荐答案

该框架提供了一个抽象的ActionFilterAttribute,您可以对其进行子类化.

The framework provides an abstract ActionFilterAttribute that you can subclass.

您可以使用操作过滤器自动验证模型状态,并在状态无效时返回任何错误:

You can use an action filter to automatically validate model state and return any errors if the state is invalid:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            context.Result = new BadRequestObjectResult(context.ModelState);
        }
    }
}

您可以将其用于单个操作或全局注册

You can either then use it on individual actions or register it globally

参考 Asp.Net Core:操作筛选器

这篇关于如何避免在每个PostBack上调用ModelState.IsValid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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