Removing a template from ASP.NET MVC actions

I have something similar in almost every action:

public ActionResult Show(int object_id)
{
    Object obj = ObjectRepository.ById(object_id);
    if (obj == null)
    {
        throw new HttpException(404);
    }
    if (obj.SomeCheck)
    {
        throw new HttpException(403);
    }
    // processing
}

The question is how to move the object, receiving (and excluding exceptions from http), away from the action and having something like this:

public ActionResult Show(Object obj)
{
    // processing
}

UPD: it is not possible to change the ObjectRepository and the model itself, it is used not only with ASP.NET, but also in other parts of the project.

+4
source share
4 answers

As others have stated, you can write filters or invoke an AOP structure such as PostSharp.

However, for some, this may be a high order. Perhaps you should consider writing something simple, convenient, and understandable that everyone on the team can immediately understand:

public ActionResult Show(int object_id)
{
    SomeClass obj = Require<SomeClass>(object_id, assumption: o => o.SomeCheck);
    // processing
}

//Perhaps: put this in a base controller or other common class
private object Require<T>(int id, Func<object, bool> assumption) where T : class
{
    var o = ObjectRepository.ById(object_id) as T;  

    //Result is required
    if (o == null) {
        throw new HttpException(404);
    }

    //Verify assumption
    if (!assumption(o)) {
        throw new HttpException(403);
    }

    return o;
}
+4
source

, :

private object GetItem(object obj) {
  Object obj = ObjectRepository.ById(object_id);

  if (obj == null) {
    throw new HttpException(404);
  }

  if (obj.SomeCheck()) {
    throw new HttpException(403);
  }

  return obj;
}

:

public ActionResult Show(int object_id) {
  object obj = GetItem(object_id);

  // processing
}
+5

+2

. , , , , , ( - yuck!) , . , , .

.

, ObjectRepository, :

public class HttpObjectService /*: IObjectService */
{
    private readonly /*I*/ObjectRepository _repository;

    public HttpObjectService(/*I*/ObjectRepository repository)
    {
        if (repository == null) throw new ArgumentNullException("repository");
        _repository = repository;
    }

    public Object ById(int id)
    {
        var obj = _repository.ById(id);
        /* Check and throw HttpExceptions */
    }
}

. , "-" , HttpExceptions , , , , , .

, , , ( ) . , - . ObjectValidator , . , .

, - , MVC, - .

+1

Source: https://habr.com/ru/post/1542366/


All Articles