AspNetCore WebApi数据验证的实现方法

发布时间:2021-02-04 16:28:33 作者:小新
来源:亿速云 阅读:175

这篇文章主要介绍AspNetCore WebApi数据验证的实现方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

前言

小明最近又遇到麻烦了,小红希望对接接口传送的数据进行验证,既然是小红要求,那小明说什么都得满足呀,这还不简单嘛。

传统验证

[HttpPost]
public async Task<ActionResult<Todo>> PostTodo(Todo todo)
{
  if (string.IsNullOrEmpty(todo.Name))
  {
    return Ok("名称不能为空");
  }
  context.Todo.Add(todo);
  await context.SaveChangesAsync();

  return CreatedAtAction("GetTodo", new { id = todo.Id }, todo);
}

小明写着写着发现这样写,很多接口相同得地方都要写,使得代码比较臃肿。

使用模型验证

在参数模型上打上注解

namespace App001.Models
{
  /// <summary>
  /// 待办事项
  /// </summary>
  public class Todo
  {
    /// <summary>
    /// ID
    /// </summary>
    public Guid Id { get; set; }
    /// <summary>
    /// 名称
    /// </summary>
    [Required(ErrorMessage = "名称不能为空")]
    public string Name { get; set; }
  }
}

Postman测试Name传值未空时,则返回:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|df184e36-4e11844dfd38a626.",
  "errors": {
    "Name": [
      "名称不能为空"
    ]
  }
}

注意Web API 控制器具有 [ApiController] 特性,则它们不必检查ModelState.IsValid。在此情况下,如果模型状态无效,将返回包含错误详细信息的自动 HTTP 400 响应。

内置特性

Error messages

通过验证特性可以指定要为无效输入显示的错误消息。 例如:

[Required(ErrorMessage = "名称不能为空")]

使用自定义返回消息格式

有两种方式:

使用自定义过滤器

首先,创建ModelValidateActionFilterAttribute过滤器。

public class ModelValidateActionFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext context)
  {
    if (!context.ModelState.IsValid)
    {
      //获取验证失败的模型字段
      var errors = context.ModelState
        .Where(e => e.Value.Errors.Count > 0)
        .Select(e => e.Value.Errors.First().ErrorMessage)
        .ToList();

      var str = string.Join("|", errors);

      //设置返回内容
      var result = new
      {
        Code = 10000,
        Msg = "未通过数据验证。",
        FullMsg = str
      };

      context.Result = new BadRequestObjectResult(result);
    }

  }
}

然后,Startup.ConfigureServices将过滤器添加到控制器中并关闭默认模型验证,另外我们还添加了AddNewtonsoftJson。

//关闭默认模型验证
services.Configure<ApiBehaviorOptions>(opt => opt.SuppressModelStateInvalidFilter = true);
services.AddControllers(opt =>
{
  //添加过滤器
  opt.Filters.Add(typeof(ModelValidateActionFilterAttribute));
}).AddNewtonsoftJson(opt =>
{
  //json字符串大小写原样输出
  opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

最后,我们看一下返回效果:

{
  "Code": 10000,
  "Msg": "未通过数据验证。",
  "FullMsg": "名称不能为空。"
}

使用默认模型验证

services.Configure<ApiBehaviorOptions>(opt =>
{
  opt.InvalidModelStateResponseFactory = actionContext =>
  {
    //获取验证失败的模型字段 
    var errors = actionContext.ModelState
      .Where(e => e.Value.Errors.Count > 0)
      .Select(e => e.Value.Errors.First().ErrorMessage)
      .ToList();

    var str = string.Join("|", errors);

    //设置返回内容
    var result = new
    {
      Code = 10000,
      Msg = "未通过数据验证。",
      FullMsg = str
    };

    return new BadRequestObjectResult(result);
  };
});

以上是“AspNetCore WebApi数据验证的实现方法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. ASPNetCore MVC ModelValidation-ajax
  2. AspNetCore WebApi如何实现数据验证

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

asp.net core webapi

上一篇:使用PHP怎么等比例放大和缩小图片

下一篇:php如何实现记事本

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》