Reputation: 10509
I need to implement the following custom action filter:
Action filter, when applied to an action CountRows
, should in it's OnActionExecuting
hander "remember" the action it is being invoked before, and redirect a client browser to a Login
action for example. But the login action should somehow know the original action that was called, so that after the login is done, it will immediatly redirect back to CountRows
.
I am guessting I can save the original action name name in filterContext
's TempData
, but how do I implement the scenario in general?
Upvotes: 3
Views: 3387
Reputation: 11235
You can do this simply with the code as follow:
[AttributeUsage(AttributeTargets.All)]
public class MyActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//write your logic
RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
redirectTargetDictionary.Add("area", "");
redirectTargetDictionary.Add("action", "Error");
redirectTargetDictionary.Add("controller", "Home");
filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
}
}
MyActionFilter redirects to link "~/Home/Error".
This example is copied (and slightly changed for the answer purposes) from link: http://www.c-sharpcorner.com/UploadFile/ff2f08/use-of-mvc-custom-action-filter/
Upvotes: 4
Reputation: 47375
You shouldn't need temp data. Ideally, your SignIn GET action should take a string returnUrl parameter. Then you can just use the filter and pass the filterContext.HttpContext.Request.RawUrl to the sign in. Have it write the redirect URL to a hidden field in the sign in form. Then when they POST, do the auth, and return a Redirect(model.ReturnUrl).
MVC actually has this behavior by default, if you decorate the protected action with an [Authorize] attribute. Technically it passes the Request.Url.Path and not the RawUrl, but the concept and result is the same.
Upvotes: 0