简体   繁体   English

WebApi数据注释验证不会出现复杂的类型参数属性

[英]WebApi data annotation validation not occuring for complex type parameter properties

I'm new to ASP.Net WebApi. 我是ASP.Net WebApi的新手。 Apologies therefore if this has been asked before (I'm unsure of the correct terminology), but I can only find this related answer which is slightly different to my problem. 因此,如果之前已经问过这个问题(我不确定正确的术语),那我很抱歉,但我只能找到我的问题略有不同的相关答案

I need to create a Post controller that accepts a complex type (a TestObject ), containing: 我需要创建一个接受复杂类型( TestObject )的Post控制器,其中包含:

  1. An IEnumerable<Person> , where Person has properties Username and ExternalId 一个IEnumerable<Person> ,其中Person具有属性UsernameExternalId
  2. Options on how the controller should handle the data (a TestOptions object) 关于控制器应如何处理数据的选项( TestOptions对象)

I have defined the classes below with data annotations to assist with validation: 我已经使用数据注释定义了以下类,以帮助验证:

public class TestObject
{
    public IEnumerable<TestPerson> TestPerson;
    public TestOptions Options;

    public void TestOject()
    {
        this.TestPerson = new List<TestPerson>();
        this.Options = new TestOptions();
    }
}

public class TestPerson
{
    [Required, MaxLength(50)]
    public string ExternalId;

    [Required, MaxLength(50)]
    public string Username;
}

public class TestOptions
{
    [Required]
    public bool Option1;

    [Required, MaxLength(50)]
    public string Option2;
}

The controller accepts TestObject and performs validation before doing anything: 控制器接受TestObject并在执行任何操作之前执行验证:

    [Route("test")]
    public HttpResponseMessage Post([FromBody] TestObject t)
    {
        if (!ModelState.IsValid)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, string.Format("Found {0} people", t.TestPerson.Count().ToString()));
        }
    }

If I use Fiddler to send a sample JSON object the with correct structures, it works fine. 如果我使用Fiddler发送一个具有正确结构的示例JSON对象,它可以正常工作。 However, if I deliberately introduce errors (Eg Username and Option2 missing) like this... 但是,如果我故意引入错误(例如,缺少UsernameOption2 )...

{
   "TestPerson":[
      { "ExternalId":"123", "Username":"Bob" },
      { "ExternalId":"123" }
   ],
   "Options":{"Option1":false}
}

I still get 我还是得到的

Status 200 状态200

2 people found 找到2个人

Why is this happening please? 为什么会这样呢? Can I use data annotation validation on complex types? 我可以在复杂类型上使用数据注释验证吗?

Update 更新

Debugging image with property values being set: 调试具有设置的属性值的图像:

在此输入图像描述

Instead of using fields you need to convert them to properties for this to work: 您需要将字段转换为属性以使其工作,而不是使用字段:

[Required, MaxLength(50)]
public string ExternalId { get; set; }

[Required, MaxLength(50)]
public string Username { get; set; }

Do this for all of your public fields. 为所有公共领域执行此操作。

Did you look at the object using the debugger and see if the fields were being set? 您是否使用调试器查看了对象并查看是否正在设置字段? They probably were, but see here for some detail on modelbinding: 他们可能是,但在这里看到有关模型绑定的一些细节:

ASP.net MVC - Model binding excludes class fields ASP.net MVC - 模型绑定不包括类字段

Update: 更新:

I have tried and tested this and am sure it will fix your issue. 我已经尝试并测试了这一点,我相信它会解决您的问题。

If you're not using TestPerson View that validator won't execute. 如果您没有使用TestPerson View,那么验证程序将无法执行。 Use 使用

if(ModelState.IsValid && TryValidateModel(model.TestPerson, "TestPerson."))
{
   //Submodel will be validated here.
}

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

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