需求:过滤验证实体
实体code:
[
StringLength
(32, MinimumLength = 1, ErrorMessage =
"{0} must be a string. Its min length is {2}, its max length is {1}."
)]
[
Required
]
public
string
OrderID {
get
;
set
; }
过滤器代码(这里会直接抛出错误信息)
public
class
ValidateModelStateFilter
:
ActionFilterAttribute
{
public
override
void
OnActionExecuted(
ActionExecutedContext
context)
{
if
(!context.ModelState.IsValid)
{
context.Result =
new
BadRequestObjectResult
(context.ModelState);
}
}
}
过滤器注入代码
public
void
ConfigureServices(
IServiceCollection
services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc(options =>
{
options.Filters.Add(newValidateModelStateFilter());
});
services.AddSingleton<
IOrderRepo
,
OrderRepo
>();
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(
new
Info
{
Version =
"v1"
,
Title =
"Zebra VMI Api"
,
Description =
"Zebra VMI Api by @360Zebra"
,
TermsOfService =
"NA"
,
Contact =
new
Contact
()
{
Name =
"斑马小二"
,
Email =
"jay.shen@360zebra.com"
,
Url =
"http://www.360zebra.com"
}
});
});