Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wire common code from a base controller in ASP.NET MVC

Tags:

asp.net-mvc

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?

like image 838
bychkov Avatar asked Aug 26 '09 22:08

bychkov


People also ask

What is default controller in MVC?

The default MVC mapping is /[Controller]/[ActionName]/[Parameters] . For this URL, the controller is HelloWorld and Welcome is the action method.

How does MVC know which controller to use?

This is because of conventions. The default convention is /{controller}/{action} , where the action is optional and defaults to Index . So when you request /Scott , MVC's routing will go and look for a controller named ScottController , all because of conventions.

What is mvc6?

MVC 6 is a part of ASP.NET 5 that has been designed for cloud-optimized applications. The runtime automatically picks the correct version of the library when our MVC application is deployed to the cloud. The Core CLR is also supposed to be tuned with a high resource-efficient optimization.


2 Answers

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 { ... });
        }
    }
}
like image 110
eu-ge-ne Avatar answered Sep 21 '22 23:09

eu-ge-ne


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");
    }
}
like image 40
Kurt Schindler Avatar answered Sep 19 '22 23:09

Kurt Schindler