一、WebApi模型验证
一、新建项目

选择空的项目webapi

查看启动端口

创建控制器


添加方法
public class VerifController : ApiController
{
public IHttpActionResult GetList()
{
dynamic data = new { name = "李白", age = };
return Json(data);
}
}
测试访问(网页get方式)

二、数据注解方式(模型验证其实还有直接判断方法)
1、创建数据Model

2、Model几种注解方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; namespace WebApi.Models
{
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; } [Range(, )]
public int Price { get; set; }
[Required]
public string Weight { get; set; }
}
}
3、更改控制器代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApi.Models; namespace WebApi.Controllers
{
public class VerifController : ApiController
{
[HttpPost]
public HttpResponseMessage GetList(Product product)
{
if (ModelState.IsValid)
{
// Do something with the product (not shown).
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
}
}
注意:必须Post,反正一般提交的数据都是Post的形式。
4、postman测试

结果如下:

4、自定义提示信息(通过过滤器方式)
1、控制器里面处理验证
建议你使用动作过滤器进行模型验证,所以你不需要太在意如何在你的api控制器中进行验证:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApi.Filters;
using WebApi.Models; namespace WebApi.Controllers
{
public class VerifController : ApiController
{ [HttpPost]
public HttpResponseMessage GetList(Product product)
{
if (ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
// the code below should probably be refactored into a GetModelErrors
// method on your BaseApiController or something like that
var errors = new List<string>();
foreach (var state in ModelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
return Request.CreateResponse(HttpStatusCode.Forbidden, errors);
} }
}
}
2、过滤器创建

完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters; namespace WebApi.Filters
{
public class ValidateModelAttribute:ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
}
注意:如果模型验证失败,则此过滤器返回包含验证错误的HTTP响应。在这种情况下,不会调用控制器操作。
关于几个引用
图一

图二

图三

图四

但是这样还是不能完全自定义格式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Newtonsoft.Json; namespace WebApi.Filters
{
public class ValidateModelAttribute:ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
var response = actionContext.Response = actionContext.Response ?? new HttpResponseMessage(); var ModelState= actionContext.ModelState;
var errors = new List<string>();
foreach (var state in ModelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
var content = new
{
success = false,
errs = errors
};
string strs = JsonConvert.SerializeObject(content);
response.Content = new StringContent(strs, Encoding.UTF8, "application/json");
return; }
}
}
}
使用方式
1、将此过滤器应用于所有Web API控制器,请在配置期间将过滤器的实例添加到HttpConfiguration.Filters集合:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ValidateModelAttribute()); // ...
}
}
2、另一种选择是将过滤器设置为各个控制器或控制器操作的属性:
public class ProductsController : ApiController
{
[ValidateModel]
public HttpResponseMessage Post(Product product)
{
// ...
}
}
官网案例:

一、WebApi模型验证的更多相关文章
- webapi - 模型验证
本次要和大家分享的是webapi的模型验证,讲解的内容可能不单单是做验证,但都是围绕模型来说明的:首先来吐槽下,今天下午老板为自己买了套新办公家具,看起来挺好说明老板有钱,不好的是我们干技术的又成了搬 ...
- ASP.NET Core - 实现自定义WebApi模型验证
Framework时代 在Framework时代,我们一般进行参数验证的时候,以下代码是非常常见的 [HttpPost] public async Task<JsonResult> Sav ...
- 一、WebApi模型验证实践项目使用
一.启语 前面我们说到,模型验证的原理(包含1.项目创建,2.模型创建,3.走通测试模型验证,4.在过滤器中处理返回json格式(非控制器内))-完全是新手理解使用的,新番理解 通常情况下,对于那些经 ...
- .Net Core WebApi 模型验证无效时报400
问题 模型验证无效时,没有进入到接口里,而是直接报400 Bad Request,非常不友好. 环境 SDK:.Net Core 2.2.401 开发工具:VS2017 step 1 创建接口 /// ...
- 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)
一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...
- .Net高级进阶,WebApi和MVC进行模型验证的时候,教你如何自由控制需要进行验证的字段?
现在,你有一个MVC架构的web项目,你要完成一个注册功能. 前台传了3个值到你的控制器,分别是账号.密码.邮箱. 如图:现在你要在控制器里面判断,账号名称.密码.邮箱不能为空,并且名称和密码不超过1 ...
- webapi Model Validation 模型验证
通常情况下,对于那些经常为别人提供数据接口的开发人员来说,对于调用方传递过来的参数都会有验证处理.例如: if (string.IsNullOrEmpty(entity.Name)) { //当姓名为 ...
- WebAPI ModelValidata(模型验证)——DataAnnotations 解析
爱做一个新的项目,在该项目中的 WebAPI 中对数据的验证用到了 ModelValidata, 以前也没有用到过,也不是很熟悉,在查看了一些资料和代码后稍有了解,这里记录下来. 这里主要介绍的是 S ...
- ASP.NET Core 2.2 WebApi 系列【八】统一返回格式(返回值、模型验证、异常)
现阶段,基本上都是前后端分离项目,这样一来,就需要前后端配合,没有统一返回格式,那么对接起来会很麻烦,浪费时间.我们需要把所有接口及异常错误信息都返回一定的Json格式,有利于前端处理,从而提高了工作 ...
随机推荐
- 00.斐波那契数列第n项
# 斐波那契数列第n项 # 1 1 2 3 5 8 def fib(n): if n <= 2: return 1 else: return fib(n-2)+fib(n-1) def fib2 ...
- ORM大结局
1.添加记录: # 一对多的添加方式: #pub_obj=Publish.objects.filter(name="橙子出版社").first() # book=Book.obje ...
- Python---基础-小游戏用户猜数字
一.10 < cost < 50 的等价表达式 cost = 40 10 < cost < 50 (10 < cost) and (cost < 50) 二.使用i ...
- 032:DTL常用过滤器(1)
为什么需要过滤器: 在DTL中,不支持函数的调用形式‘()’,因此不能给函数传递参数,这将有很大的局限性:而过滤器其实就是一个函数,可以对需要处理的参数进行处理,并且还可以额外接受一个参数(也就是说: ...
- Jenkins配置git/github 插件的ssh key
参考来源:http://jingyan.baidu.com/article/a65957f4f0acc624e67f9bc1.html 方式一:本地需要生成公私钥文件,git/github中新建ssh ...
- datatables屏蔽警告弹窗
//不显示任何错误信息 $.fn.dataTable.ext.errMode = 'none'; //以下为发生错误时的事件处理,如不处理,可不管. $('#tableId').on( 'error. ...
- Centos中文语言乱码解决方法
vim /etc/locale.conf 添加:LANG="zh_CN.UTF-8" 执行一下source /etc/locale.conf,使刚修改的文件生效
- OC+RAC(六) 核心方法bind
-(void)_test6{ RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> ...
- Elasticsearch6.5安装&&常见问题与答案解释
ElasticSearch是一个用Java开发的基于Lucene的搜索服务器.它可以提供一个分布式多用户能力的全文搜索引擎,基于RESTfulweb接口.现阶段它主要为Apache许可条款下的开放源码 ...
- 不缓存JS
方法一:告诉浏览器不要缓存(不一定好使) <meta http-equiv="Pragma" content="no-cache"> <met ...