Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Global redirect based on logic in ASP.NET MVC3

I am building an ASP.NET MVC3 computer support ticketing portal.

There is a maintenance state, where it is best to forbid the users from interacting with EF/Database, to avoid "collisions" I am currently getting.

I have an IMaintenanceDispatcher that has a boolean property IsOnMaintenance set to true by the business logic, whenever a background logic puts the portal in that state.

I need to redirect client requests to a parking page for the time of maintenance.

Where do I place the logic that will check if the IsOnMaintenance is true, and if so, do a redirect to a URL?

Upvotes: 1

Views: 1385

Answers (1)

ten5peed
ten5peed

Reputation: 15890

You could put it in an ActionFilterAttribute and apply that attribute to any applicable actions/controllers or globally.

public class IsOnMaintenanceAttribute : ActionFilterAttribute
{
    //You'll need to setup your IoC to inject this
    public IMaintenanceDispatcher InjectedMaintenanceDispatcher { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        object ticketIdObj;
        if (!filterContext.ActionParameters.TryGetValue("ticketId", out ticketIdObj))
            return;

        //Make sure it exists
        if (InjectedMaintenanceDispatcher.IsOnMaintenance(int.parse(ticketIdObj)))
        {
            var routeValues = new RouteValueDictionary(new {
                action = "parkingpage",
                controller = "maintenance",
                area = "ticket" });

            filterContext.Result = new RedirectToRouteResult(routeValues);
            return;
        }
    }
}

Note, your action method parameters needs to contain a variable named ticketId for the filterContext.ActionParameters.TryGetValue to work.

Note: I had assumed that an individual ticket is put into maintenance mode and you were wanting to check for that... but re-reading the question it seems like you want to put the whole area/site on hold. Even with that case, the ActionFilterAttribute example still holds... just not as different.

Upvotes: 1

Related Questions