繁体   English   中英

WebApi视图模型验证不起作用

[英]WebApi viewmodel validation not working

我一直在努力尝试让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它始终会始终返回“确定” ...

ValidateModelAttributeWebApiConfig注册

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均未更改任何内容

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

这很好

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

        return "not ok";
    }

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

同样,自定义的ValidateModelAttributeValidateModelAttribute过时,尽管如果要在ViewModel无效时系统地引发异常,它仍然很有用。 我宁愿只是在代码中处理它就能返回自定义错误对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM