I have an MVC project i which the user can change language from a menu. The controller code:
[HttpGet]
public ActionResult ChangeLanguage(string Language)
{
Response.Cookies[SessionParams.LANGUAGE].Value = Language;
Response.Cookies[SessionParams.LANGUAGE].Expires = DateTime.Now.AddDays(7);
return Redirect(Request.UrlReferrer.PathAndQuery);
}
and the Global.asax.cs code:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (Request.Cookies[SessionParams.LANGUAGE] != null)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.Cookies[SessionParams.LANGUAGE].Value);
}
}
This works great. Now I added a class that implements IAuthorizationFilter to make sure that I can check whether the session is still valid before every request (FilterConfig.cs):
public class ConnectedUserValidAuthorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
UrlHelper urlHelper = new UrlHelper(filterContext.HttpContext.Request.RequestContext);
string loginUrl = urlHelper.Action("Login", "Account");
if (filterContext.HttpContext.Request.Url.AbsolutePath != loginUrl)
{
if (filterContext.HttpContext.Session[SessionParams.CONNECTED_USER] == null)
filterContext.HttpContext.Response.Redirect("~");
}
}
}
For some reason, after I add the filter to the global filters:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ConnectedUserValidAuthorizationFilter());
}
Debugging shows that Request.Cookies
in Global.asax.cs no longer holds value for the language
cookie.
Removing the filter brings the value back.
Any idea how to resolve it? I tried moving the filter code to Application_BeginRequest
, but the session does not exists yet in that context.
I ended up implementing
IActionFilter
instead ofIAuthorizationFilter
interface, with the same logic used inOnAuthorization
, insideOnActionExecuting
function.This seems more appropriate for the task, since
OnActionExecuting
is called before every Action request. It also seems to keep the cookies intact.