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

前端 未结 3 1544
陌清茗
陌清茗 2021-01-05 09:23

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

相关标签:
3条回答
  • 2021-01-05 09:29

    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");
        }
    }
    
    0 讨论(0)
  • 2021-01-05 09:38

    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 { ... });
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-05 09:41

    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.

    0 讨论(0)
提交回复
热议问题