Validating business logic in Asp.net MVC using exceptions

I have a question regarding the method that I use to do business rule checks in asp.net mvc.

I currently have an exception class that looks something like this:

public class ValidationException : Exception 
{
    private ModelStateDictionary State { get; set; }
    public ValidationException(ModelStateDictionary state)
    {
        State = state;
    }
    public void MergeModelStates(ModelStateDictionary state)
    {
        state.Merge(this.State);
    }
}

and a validator that looks like this:

public void Validate(IEntity entity)
{
    ModelStateDictionary state = new ModelStateDictionary();
    if (entity.Contact != null && _service.GetBy(entity.Contact.Id) == null)
        state.AddModelError("Contact", "Invalid Contact.");
    if (entity.Title.Length > 8)
        state.AddModelError("title", "Title is too long...");
    ... etc
    if (!state.IsValid)
        throw new ValidationException(state);
}

and a controller that does something like this

public ActionResult Add()
{
    var entity = new InputModel;
    try
    {
        TryUpdateMode(inputModel);
        ..... Send input to a Repository (Repository calls Validate(entity);
    }
    catch (ValidationException validationException)
    {
       validationException.MergeModelStates(this.ModelState);
       TryUpdateModel(inputModel);
       return View("Add",inputModel);
    }
    return View("List");
}

Is it wrong to use an exception to do something like this? Are there any examples of a better method? I really do not want to add validation to the model object itself. The only other way I've seen is to bring the ModelState controller to the repository level, but that seemed messy to me.

Thanks for any help

+5
source share
2

, , , , . - :

  • . - , .
  • . , , " " - , .
  • , . - , , , . , , , , , .

, , - Validate, ( ), Save, Validate() , - . "throw, ", ", , ".

Validate vs. Save - throwing Save() , Validate(). , - , , . , , :

ValidationResult result = obj.Validate();
if (result.IsValid) {
   obj.Save();
} else {
   // display errors to the user
}

, . , , . , , - .

+13

ASP.NET MVC 2: -

http://stephenwalther.com/blog/archive/2008/09/10/asp-net-mvc-tip-43-use-data-annotation-validators.aspx

http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx

: -

public class Person
{
  [Required(ErrorMessage="Please enter a name.")]
  public String Name { get; set; }
}

, :

Controller ModelState ( , ) , AddModelError, , if ( ModelState.IsValid) : -

var entity = new InputModel();

TryUpdateModel(entity);
MyValidator.Validate(entity, ModelState);

if(ModelState.IsValid) { ...

: -

public void Validate(IEntity entity, ModelStateDictionary state)
{
  if (entity.Contact != null && _service.ValidId(entity.Contact.Id) == null)
    state.AddModelError("Contact", "Invalid Contact.");
  // etc
}
+2

All Articles