Setting TempData within a ActionFilterAttribute
I have a custom action filter, that inside the OnActionExecuting
, depending on certain criteria, logs out a user and redirects them to the home page of the site. The (stripped back) code for the redirect part is below
filterContext.Controller.TempData.Add("key", "Message");
filterContext.Result = new RedirectResult("/");
As above, i am also setting a tempData message. Because the user has been logged out, when they hit the home page, the [Authorize]
attribute will redirect them to the login GET page. On the login view, i am displaying any messages from within tempData. However in this situation the tempData is empty.
This is very similar behavior to how my login POST works (if invalid, it redirects to home, which redirects to login and displays the tempData message that was set in the Login post). This code can be seen below
TempData.Add("key", errorMessage);
return Redirect("/"));
The reason i am doing it this way, rather than redirecting specifically to the login page is because this code is distributed across many sites, so we dont know what the login GET url is.
Does anyone have any information as why this is working for the Login POST but not for the ActionFilter Redirect?
Edit:
If i remove the logout call within the custom action filter, the tempData is still set within the Home action - however this doesnt explain why it works for the Login POST but not the action filter?
So it turns out that when i was logging out the user from the system, i was also abandoning the session (calling HttpContextBase.Session.Abandon()
) and also resetting the cookie session id. These were affecting the TempData behavior. By removing these calls, the tempData is now correctly set and displayed.
setting the result to new RedirectResult("/")
will cause the current server-processing to stop ,and send the client a responce, that tells the client to request a new URL - the one you had said in the RedirectResult. The second request is then different, and does not contain the values from the previous processing. Try using Redirect("/");
or Server.Transfer("/");
to service the new route in the same client request.