.Net国际化

.Net下国际化很好做但是这种方式却不便于维护咯,有空研究下怎么能提高国际化的效率咯,先写下简单实现的思路

新建global.en-us.resx 和 global.resx 两个资源文件

创建一个继承于PAGE类的基类

 

public class BaePage : Page
{


        
public BaePage()
        
{
            
//TODO:页面基类
        }


        
//国际化
        protected override void InitializeCulture()
        
{
            
string UserCulture = string.Empty;

            
//判断当前语言
            if (Request.Cookies["global"] == null)
            
{
                UserCulture
= Request.UserLanguages[0].ToString().Trim();
                CreateCookies(UserCulture);
            }

            
else
            
{
                UserCulture
= Request.Cookies["global"].Value.ToString().Trim();
            }


            
//设置显示语言
            if (UserCulture != string.Empty)
            
{
                Thread.CurrentThread.CurrentUICulture
= new CultureInfo(UserCulture);
                Thread.CurrentThread.CurrentCulture
= CultureInfo.CreateSpecificCulture(UserCulture);
            }

            
else
            
{
                Thread.CurrentThread.CurrentUICulture
= new CultureInfo("en-US");
                Thread.CurrentThread.CurrentCulture
= CultureInfo.CreateSpecificCulture("en-US");
            }


            
base.InitializeCulture();
        }


        
//创建存储语言的cookies
        public void CreateCookies(string language)
        
{
            HttpCookie cook
= new HttpCookie("global");
            cook.Value
= language;
            cook.Expires
= DateTime.MaxValue;
            Response.Cookies.Add(cook);
        }


        
///
        
/// 判断当前的语言
        
///
        
///

        public string GetLanguage()
        
{
            
string UserCulture = string.Empty;
            
if (Request.Cookies["global"] == null)
            
{
                UserCulture
= Request.UserLanguages[0].ToString().Trim();
                CreateCookies(UserCulture);
            }

            
else
            
{
                UserCulture
= Request.Cookies["global"].Value.ToString().Trim();
            }

            
return UserCulture;
        }


}

 

然后创建网页 Default.aspx 如下:

     < form id = " form1 " runat = " server " >
    
< div >
                    
< asp:Button ID = " btnChinese " runat = " server " CommandArgument = " zh-CN " Text = " 中文 " OnClick = " Language_Click " />
                
< asp:Button ID = " btnEngLish " runat = " server " CommandArgument = " en-US " Text = " English " OnClick = " Language_Click " />
                
< hr />
        
< asp:Label ID = " lblShow " runat = " server " Text = " " >asp:Label>
    
div>
    
form>

在Default.aspx.cs里写事件:

protected void Language_Click( object sender, EventArgs e)
        
{
            Button objButton
= sender as Button;
            
string language = objButton.CommandArgument;
            CreateCookies(language);
            Response.Redirect(Request.RawUrl);
        }

就搞定了咯,不过要记着要Default要继承BasePage类

你可能感兴趣的:(.net)