I'm currently looking for a better solution to what I have now. I hoping someone could help me on this one.
I'm creating a web page and I'm trying to set the culture of the website manually with cookies.
I have 2 buttons
<asp:ImageButton runat="server" ID="LanguageNL" OnCommand="Language_Command" CommandName="Language" CommandArgument="nl" ImageUrl="~/Images/Flags/nl.png" style="margin-left: 0px" />
<asp:ImageButton runat="server" ID="LanguageEN" OnCommand="Language_Command" CommandName="Language" CommandArgument="en" ImageUrl="~/Images/Flags/gb.png" style="margin-left: 5px" />
protected void Language_Command(object sender, CommandEventArgs e)
{
Response.Write("Do Command");
HttpCookie cookie = new HttpCookie(e.CommandName);
cookie.Value = e.CommandArgument.ToString();
cookie.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookie);
Response.Redirect(Request.RawUrl);
}
and to set the page culture I'm using a IHttpModule like this
using System;
using System.Globalization;
using System.Threading;
using System.Web;
public class DartsGhentAuthorization : IHttpModule
{
public DartsGhentAuthorization() { }
public void Init(HttpApplication context)
{
context.BeginRequest += Context_BeginRequest;
}
private void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
application.Response.Write("Begin Request");
HttpCookie languageCookie = application.Request.Cookies["Language"];
CultureInfo culture = new CultureInfo("nl");
if (languageCookie != null)
culture = new CultureInfo(languageCookie.Value);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
public void Dispose() { }
}
Now the problem I'm facing happens in the page life cycle. When I press a button to change the language, the page refreshes but first the HttpModule is called and only after that the page load and then the button commands are triggered. Which means I first look for the culture and only later I set the language in one page request. To fix my problem I added a response.redirect to reload my page so the language is changed as intended but is there a way to do this better?
I'm using HttpModule because I'm trying not to set the page culture in an overload. Also I'm creating my own page authorization so I will need the httpmodule for more website integration.