用cookie设置httpmodule中的文化



我目前正在寻找更好的解决方案。我希望有人可以帮助我。

我正在创建一个网页,我正在尝试用cookie手动设置网站的文化。

我有2个按钮

<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);
    }

并设置我使用的ihttpmodule的页面文化

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() { }
}

现在我面临的问题发生在页面生命周期中。当我按下按钮更改语言时,页面会刷新,但是首先,httpmodule被调用,只有之后,页面加载,然后触发按钮命令。这意味着我首先要寻找文化,只有以后我在一个页面请求中设置了语言。为了解决我的问题,我添加了一个响应。重新加载我的页面重新加载,以便按预期更改语言,但是有办法做得更好吗?

我正在使用httpmodule,因为我试图在超载中不设置页面文化。另外,我正在创建自己的页面授权,因此我需要httpmodule来进行更多的网站集成。

您可以在JavaScript的帮助下向您的ASP按钮添加一些骇客,以清除您的cookie,以便在请求开始之前,您没有包含该语言的cookie,因此它将设置新的cookie这是示例

<asp:ImageButton runat="server" ID="LanguageNL" OnClientClick="ClearCookie();"  OnCommand="Language_Command" CommandName="Language" CommandArgument="nl" ImageUrl="~/Images/Flags/nl.png" style="margin-left: 0px" />
<asp:ImageButton runat="server" OnClientClick="ClearCookie();" ID="LanguageEN" OnCommand="Language_Command" CommandName="Language" CommandArgument="en" ImageUrl="~/Images/Flags/gb.png" style="margin-left: 5px" />

在您的JavaScript添加功能清除cookie

function ClearCookie(){
//Do Clear Cookie
}

最新更新