开发者

Inject referrer action via action filter?

Is there a way to inject the referrer action from an action filter? Lets say I have a view that comes from action X. In dies view I call action Y and I w开发者_运维问答ant to redirect again to action X. (There are multiple X actions that call action Y). I thought that it could be nice if I had a parameter call referrerAction and an action filter that filled it with the previous action. Is it possible?

Thanks.


Here's how I do:

  public class ReturnPointAttribute : Attribute
  {
  }

  public class BaseController: Controller
  {
      private string returnPointUrl = null;
      protected override void OnActionExecuted(ActionExecutedContext filterContext)
      {
         base.OnActionExecuted(filterContext);
         if (filterContext.ActionDescriptor.IsDefined(typeof(ReturnPointAttribute), true))
            returnPointUrl = filterContext.HttpContext.Request.Url.ToString();
      }
      public ActionResult RedirectOrReturn<T>(Expression<Action<T>> action) where T : BaseController
      {
         return returnPointUrl.IsNullOrEmpty() 
            ? MyControllerExtensions.RedirectToAction(this, action) 
            : (ActionResult)Redirect(returnPointUrl);
      }
   }

Now, you mark you X actions with [ReturnPoint] and call RedirectOrReturn() if you want to return back.

I do not use UrlReferrer because it can be wrong and I have no control over its value. With ReturnPoint, you can also have groups, e.g. [ReturnPoint("Orders")] and RedirectOrReturn("Orders").

Of course, you can have more automatic behaviour in OnActionExecuted - e.g. it can check if returned result is Redirect, and automatically go to ReturnPoint if it has value. Or you can control this with [ReturnPoint(Automatic=true)], and so on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜