Why are ApiController and Controller's ModelState are so different?

本文探讨了使用ASP.NET Web API构建项目时遇到的问题:如何正确返回服务器端模型验证消息。通过对比Web API控制器与MVC控制器的行为差异,分析了不同环境下模型状态的实现方式及原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Recently I use ASP.net Web API to build a small project. I met some problems in returning server side model validation messages. Then I built a small test project and created a model like that:

    public class Contact : IValidatableObject
    {
        [Required]
        public string FullName { get; set; }

        [RegularExpression(@"^\d[-,\d]*\d$", ErrorMessage = "Phone number is incorrect.")]
        public string PhoneNumber { get; set; }

        [RegularExpression(@"^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$", ErrorMessage = "Email format is incorrect.")]
        public string Email { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (this.Email == null && this.PhoneNumber == null)
                yield return new ValidationResult("Email and phone number can not both be empty.", new string[] { "PhoneNumber", "Email" });
        }
    }

I also created two controllers to test it. The Web API controller:

    public class ContactController : ApiController
    {
        public HttpResponseMessage Post([FromBody]Contact ct)
        {
             HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK);
             msg.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(ModelState));
             return msg;
        }
    }

The MVC controller:

    public class ContactMvcController : Controller
    {
        [HttpPost]
        public ActionResult Contact(Contact ct)
        {
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(ModelState));
        }
    }

After that, I use fiddler to post a request to test it:

Http headers ----
content-type: application/json
Content-Length: 28

Http content ----
{"FullName":"Jiang Guogang"}

Then I got very different result. The MVC controller:

Noticing that all properties are contained in result whatever it has error or not. And look at the Web API controller:

That's strange. I want to know the reason why they are so different.

Personally, I think the MVC controller does better.

I also compared the prototype of the two ModelStates. They are little difference althought they are in different namespaces and libraries.

MvcController's ModelStatenamespace System.Web.MvcSystem.Web.Mvc.dll
Web API Controller's ModelStatenamespace System.Web.Http.ModelBindingSystem.Web.Http.dll


Does that make sense?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值