WebApi视图模型验证无效

时间:2015-07-28 10:06:10

标签: c# asp.net-web-api

我一直试图让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都没有改变任何内容

1 个答案:

答案 0 :(得分:2)

简单的MVC控制器似乎没有问题,在这个web api示例中,我们显然必须指定[FromUri]

这很好用

    [HttpGet]
    public string Test([FromUri]TestViewModel email)
    {
        if (ModelState.IsValid)
        {
            return "ok";
        }

        return "not ok";
    }

使用此代码,我现在还可以实现jsonP行为

自定义ValidateModelAttribute也已过时,但如果您想在ViewModel无效时系统地抛出异常,它仍然有用。我宁愿在代码中处理它以便能够返回自定义错误对象。

相关问题