【发布时间】:2015-07-28 20:14:01
【问题描述】:
我一直在努力尝试让 ViewModels 使用 webapi 2.2 进行验证
从文档..它应该工作: http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
namespace WebApplication3.Controllers
{
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
public class TestViewModel
{
[Required]
[EmailAddress]
[MinLength(3)]
[MaxLength(255)]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
public class ValuesController : ApiController
{
[ValidateModel]
[HttpGet]
public string Test(TestViewModel email)
{
if (ModelState.IsValid)
{
return "ok";
}
return "not ok";
}
}
}
无论有没有ValidateModelAttribute,它都会一直返回“ok”...
ValidateModelAttribute 注册在WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Filters.Add(new ValidateModelAttribute());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
有人知道这里发生了什么吗?使用DataAnnotations 预验证数据要简单得多。
样品请求:
http://localhost:55788/api/values/Test?email=ss
返回:ok
GET/POST 都不会改变任何东西
【问题讨论】:
-
ModelState.IsValid已经为你做这件事了 -
[HttpPost] 尝试发帖。而不是 [HttpGet]
-
@AmitKumarGhosh ModelState.IsValid 什么也没做,我传递了一封无效的电子邮件,它仍然返回正常
-
你会发现 email 为空,所以它的状态无效,所以我必须检查参数是否为空 && ModalState.IsValid
标签: c# asp.net-web-api