ASP.NET Web API之FluentValidation验证
来源:互联网 发布:银行卡网络异地消费 编辑:程序博客网 时间:2024/06/08 05:10
最近在做Web API,用到了流式验证,就简单的说说这个流式验证。
首先我们定义一个Filter,如下
1
2
3
4
5
6
7
8
9
10
11
public
class
ValidateResponseFilterAttribute : ActionFilterAttribute
{
public
override
void
OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if
(!actionContext.ModelState.IsValid)
{
//actionContext.ModelState.Keys
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
重写Action执行方法,如果请求model存在异常,则将500error返回给客户端。
接下来我们要怎么做,定义一个BaseController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[ValidateResponseFilter]
public
class
BaseController : ApiController
{
protected
HttpResponseMessage CreateSystemErrorResponse(
string
errorMsg)
{
return
Request.CreateResponse<
object
>(
new
{
IsSuc =
false
,
ErrorMsg = errorMsg
});
}
protected
HttpResponseMessage CreateErrorResponse(
string
responseCode, Type type =
null
, HttpStatusCode statusCode = HttpStatusCode.OK)
{
return
Request.CreateResponse<
object
>(statusCode,
new
{
IsSuc =
false
,
ErrorMsg = MessageResHelper.GetMessage(type !=
null
? type.Name :
this
.GetType().Name, responseCode)
});
}
protected
HttpResponseMessage CreateSucResponse(
string
responseCode =
""
)
{
if
(
string
.IsNullOrEmpty(responseCode))
{
return
Request.CreateResponse<
object
>(
new
{
IsSuc =
true
});
}
return
Request.CreateResponse<
object
>(
new
{
IsSuc =
true
,
ErrorMsg = MessageResHelper.GetMessage(
this
.GetType().Name, responseCode)
});
}
}
在BaseController上我们标记上面的Attribute,验证不通过进行请求拦截,然后所有的APIController都继承BaseController,这样所有继承自BaseController的Controller都会走验证。
接下来我们看一下Request的定义
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public
class
CustomerValidateRequest : IValidatableObject
{
private
readonly
IValidator _validator;
public
CustomerValidateRequest()
{
_validator =
new
CustomerValidateRequestValidator();
}
public
string
Email {
get
;
set
; }
public
string
Password {
get
;
set
; }
public
string
ValidateCode {
get
;
set
; }
public
IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return
_validator.Validate(
this
).ToValidationResult();
}
}
Request定义好之后,我们在最下面写方法获取验证的结果。接下来再看看我们的Validator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public
class
CustomerValidateRequestValidator : AbstractValidator<CustomerValidateRequest>
{
public
CustomerValidateRequestValidator()
{
RuleFor(dto => dto.Email).NotNull().NotEmpty();
RuleFor(dto => dto.Password).NotNull().NotEmpty();
RuleFor(dto => dto.ValidateCode).NotNull().NotEmpty().Length(WebAppSettings.ValidateCodeLength);
When(dto => !
string
.IsNullOrWhiteSpace(dto.Email), () =>
{
RuleFor(c => c.Email).Matches(
@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
);
});
}
}
在这里就是我们所要验证的逻辑,可以验证最基本的非空,长度,还可以验证正则。这里RuleFor返回的是如下的接口类型
1
public
IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression)
该接口继承IRuleBuilder接口
1
public
interface
IRuleBuilderInitial<T,
out
TProperty> : IFluentInterface, IRuleBuilder<T, TProperty>, IConfigurable<PropertyRule, IRuleBuilderInitial<T, TProperty>>
IRuleBuild有很多扩展方法在DefaultValidatorExtensions类中,如下
简直是太多了,验证信用卡,邮箱,比较大小,区域,不等于等等,当然你自己也可以扩展一些出来。
我们用Google DHC看一下效果
如果什么都不传,就会根据上面的验证规则进行验证。
如果传了Email,则会验证Email是否正确。
最后记得在Globle.asax.cs中增加如下代码,注意在Nuget中找到FluentValidation和FluentValidation.MVC
1
2
3
4
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes =
false
;
ModelValidatorProviders.Providers.Add(
new
FluentValidationModelValidatorProvider(
new
AttributedValidatorFactory()));
ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;
FluentValidationModelValidatorProvider.Configure();
原文转自:乐搏学院http://www.learnbo.com/front/article/cmsIndex
- ASP.NET Web API之FluentValidation验证
- ASP.NET MVC中使用FluentValidation验证实体
- .NET模型验证组件FluentValidation
- ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)
- ASP.NET Web API(二):安全验证之使用HTTP基本认证
- ASP.NET Web API:安全验证之使用HTTP基本认证
- ASP.NET Web API:安全验证之使用摘要认证(digest authentication)
- asp.net之使用web API
- ASP.NET Web API 之 WebApiConfig
- ASP.NET Web API 之 ValuesController
- 【ASP.NET Web API教程】6.4 模型验证
- asp.net web api
- ASP.NET Web API
- asp.net web api
- asp.net web api
- asp.net web api
- NET MVC5第三方验证——FluentValidation
- 模型验证组件 FluentValidation
- Hibernate的Session详解(transaction)
- 简单的Linux系统命令
- 对数几率回归Logistic Regression(Matlab)
- Android LinearLayout(7.1) 源码解析
- 数据库创建表
- ASP.NET Web API之FluentValidation验证
- Notepad++配置Python开发环境
- Bmob解决移动端后台服务实现方案
- 玩转EXCEL系列-选择性粘贴几个实用技巧
- VC中常用的宏
- UCOS-II任务设计
- STL源码剖析-关联式容器之set,map,multiset和multimap
- 数据库数据的插入
- Linux内核设计与实现(9)---中断处理的下半部