ASP.Net C# validating model based on MetadataType

2019-02-07 15:08发布

问题:

My team is building ViewModels with model validation inside the MetadataType. My question is that I'm using a non-MVC project, can I use it to validate the model? If yes, can you please give an example?

[MetadataType(typeof(PersonMetadata))]
public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}
 public class PersonMetadata
 {
        [StringLength(255, ErrorMessage="Name is required"), Required]
        [DisplayName("Name")]
        public string Name { get; set; }
 }

Thank you in advance!

回答1:

I don't think this is a good way to do things. In general, using Metadata classes is a design smell. I was recently turned on to Fluent Validation for .NET, which looks very promising, is pluggable for MVC but does not require MVC.

All that being said, it is doable:

        var person = new Person(); 
        var controllerSlashValidator = new FakeControllerValidator();
        ModelStateDictionary modelStateDictionary;
        bool isValid = controllerSlashValidator.Validate(person,out modelStateDictionary);

this code would need the FakeControllerValidator below

    public class FakeControllerValidator: Controller
    {
        public FakeControllerValidator()
        {
            this.ControllerContext = new ControllerContext(new RequestContext(new HttpContextWrapper(System.Web.HttpContext.Current),new RouteData()),this);
        }
        public bool Validate(object model, out ModelStateDictionary modelStateDictionary)
        {
            bool isValid = TryValidateModel(model);
            modelStateDictionary = ModelState;
            return isValid;
        }
    }