【问题标题】:WebApi viewmodel validation not workingWebApi 视图模型验证不起作用
【发布时间】: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


【解决方案1】:

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

这很好用

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

        return "not ok";
    }

有了这段代码,我现在也可以实现 jsonP 行为了

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多