Separating validation logic from business logic in asp.net MVC 5 controller

a 夏天 提交于 2019-12-12 02:19:26

问题


I have an asp.net MVC 5 website.

I am using data annotations on the model for validation - eg

[Required]
public string FirstName { get; set; }

However, if I want to do something a bit more complicated with validation, say require a date to be in the future - all examples I have seen just perform validation in the controller - eg:

[HttpPost]
public ActionResult Edit(MyViewModel vm)
{
    // check date is in future
    if (vm.mydate < DateTime.Now())
        ModelState.IsValid = false;

    if (ModelState.IsValid)
    {
        //Business Logic
    }

Even Web Forms let you separate validation logic out into a CustomValidator. It feels wrong putting validation logic into a controller directly and mixing it with business logic.

(note - while I would like an answer to how to do this specific problems with Data Annotations - I would also like an answer to the bigger question about separating validation logic out).

Is there a best practice, or a Framework mandated, way to separate this out? I haven't seen it in any example sites found online.

Am I unduly worrying about this - is this part of the purpose of a controller to perform validation? Should my business logic instead be in the Model? (the BL is largely really just writing to a database so maybe that doesn't even count as BL?).

thx.


回答1:


You need to implement your custom Validation Attribute.

Create a new class and add:

public sealed class ValidFutureDate : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            DateTime InputDate = Convert.ToDateTime(value);

            if (InputDate <= DateTime.Now)
            {
                return new ValidationResult("Inputed date must be in the future.");
            }
        }
        return ValidationResult.Success;
    }
}

You need to add a reference to System.ComponentModel.DataAnnotations

And in your ViewModel, you can use the attribute like all the rest:

[Required]
[ValidFutureDate]
public DateTime Date { get; set; }


来源:https://stackoverflow.com/questions/40135387/separating-validation-logic-from-business-logic-in-asp-net-mvc-5-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!