Question

i have built an api and need to validate input objects passed as parameters to controller actions. Sometimes the same input class will have differing compulsory properties for different actions.

so

public class test
{
public ActionResult Create(User user)
{
  //here user_name must be present but no user_id
}
public ActionResult Delete(User user)
{
  //here only user_id must be present.
}
}

I have had a look at fluentValidation.net but it seems one has to create rules on a per class basis not class/action.

thanks.

Was it helpful?

Solution

What is a User?

I don't mean in the sense of where is the class defined, but in the sense of what does it physically mean in the domain? It sounds like you're trying to get it to mean multiple things.

Instead of trying to fit these actions into a model for the domain, create action models for them. Something like this:

class CreateUserAction
{
  public string Username {get; set;}
}

class DeleteUserAction
{
  public int ID {get; set;}
}

Then use these in your action methods:

public ActionResult Create(CreateUserAction user)
{
}

public ActionResult Delete(DeleteUserAction user)
{
}

This will break out the different purposes into different classes, in accordance with the single responsibility principle. Now the User class can focus on simply representing a user object, as opposed to sometimes representing a not-yet-created user or sometimes representing only the ID of a user object, etc.

One major benefit here is that you can specify the validation rules directly in the class. With this approach, a User object can always require a Username and an ID to be valid. Whereas a CreateUserAction object doesn't even have an ID (since it doesn't need one) and a DeleteUserAction object doesn't have a Username (since it doesn't need one).

You can further add additional fields as needed. For example, the CreateUserAction object will likely have other fields to describe the user being created. (It may even have fields that don't go on a User object at all, but would be translated into some other object in the domain.) However, the DeleteUserAction may never need anything more than an ID (and, as suggested by SLaks, can probably be replaced with just an int for that action method, but that's up to you).

Clearer roles and responsibilities for classes, fewer partially-initialized half-objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top