tags:

views:

183

answers:

3

My ASP.NET MVC application is a small part of a bigger ColdFusion app that is going to be soon replaced completely. I'm passing some parameters from ColdFusion part through cookies and need to check for this information before I run every action. In case if the information is missing I need to redirect to the parent site. What is the best place to put this functionality and how to call it uniformally?

Currently, I have implemented a base controller and in every action method I call a method from the base controller and based on the return result either redirect or continue with action. This approach seems to work but it clutters my action methods with consern not directly related to the action. How could I separate it out, are there any lifecycle events for controller I could tap into?

+1  A: 

If this is necessary on every action within a particular controller, one potential option you could probably use is to just do this in the base controller...

public class MyBaseController: Controller
{
    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);

        var cookie = base.Request.Cookies["coldfusioncookie"];
        //if something is wrong with cookie
            Response.Redirect("http://mycoldfusionapp");
    }
}
Kurt Schindler
A: 

The better approach would be to implement a custom ActionFilterAttribute and override the OnActionExecuting method to handle the logic and then just decorate your actions with the attribute.

public class CheckCookieAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Check your cookie and handle the redirect here, otherwise, do nothing
        // You can get to your cookie through the filterContext parameter
    }
}

public class ActionController : Controller
{
    [CheckCookie]
    public ActionResult GetFoo()
    {
        return View();
    }
}

Hope this helps.

Dale Ragan
Kurt's answer seems more logical since this will be performed on EVERY action. If it was only certain actions, your approach would be better.
Martin
No worries Martin. If you need it for every action, then I would suggest what eu-ge-ne answered with. I was about too, but then I saw his answer.
Dale Ragan
+2  A: 

If you already implemented a base controller just override its OnActionExecuting() method:

public class YourBaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if(somethingIsWrong)
        {
            filterContext.Result = new RedirectToRouteResult(
                new System.Web.Routing.RouteValueDictionary { ... });
        }
    }
}
eu-ge-ne