views:

43

answers:

1

Hey everyone,

I've been working on a rather large web application that requires a specific id param in the url for every page visited (for example, /controller/action/id?AccountId=23235325). This id has to be verified every time someone visits a page.

I want to reduce code replication as much as possible, and was wondering if there is a way to use an init method or constructor in a controller that inherits the MVC controller, and then have that controller extended by the others.

I'm using ASP.NET MVC 2.

+3  A: 

Yes this is possible using either a base controller class that all your controllers inherit or by creating a custom attribute that you decorate your controller with.

Base controller:

public class BaseController : Controller
{

   protected override void Initialize(System.Web.Routing.RequestContext requestContext)
   {
       // verify logic here
   }
}

Your controllers:

public class AccountController : BaseController
{
      // the Initialize() function will get called for every request
      // thus running the verify logic
}

Custom Authorization Attribute:

public class AuthorizeAccountNumberAttribute : AuthorizationAttribute
{
    protected override AuthorizationResult IsAuthorized(System.Security.Principal.IPrincipal principal, AuthorizationContext authorizationContext)
    {
           // verify logic here
    }
}

On your controller(s):

[AuthorizeAccountNumber]
public class AccountController : Controller
{
      // the IsAuthorized() function in the AuthorizeAccountNumber will 
      // get called for every request and thus the verify logic
}

You can combine both approaches to have another custom base controller class which is decorated with the [AuthorizeAccountNumber] which your controllers that require verification inherit from.

Baddie