---
title: "asp.net中url地址传送中文参数时的两种解决方案(downmoon)"
author: "netxdiy"
date: "2007-11-14T17:26:00Z"
tags: []
slug: "asp-net-url-downmoon"
draft: false
lastmod: "2012-09-27T11:31:40Z"
id: 1687112
url: "https://netxdiy.iteye.com/blog/1687112"
---

前天遇到一个地址传递中文参数变为乱码的问题，同样的两个web Project,一个是vs2003,一个是vs2005,前者可以，后者就是不可以。  
在Web.comfig中配置 是一样的：

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt; globalization requestEncoding ="gb2312" responseEncoding ="gb2312" /&gt;

页面Header部分也都有

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt; meta http-equiv ="Content-Type" content ="text/html;charset=gb2312" /&gt;

真是奇怪，  
只好用了笨办法：  
写参数：

string strurl = PreUrl + " ?word={0}&sort={1}&check={2} " ;  
strurl = string .Format(strurl,HttpUtility.UrlEncode( this .txtSearchTxt.Text.Trim(),System.Text.Encoding.GetEncoding( " GB2312 " )), this .radioSortDesc.SelectedIndex.ToString(),CheckState.ToString());  
Page.Response.Redirect(strurl);  
// 注意编码方式为gb2312

读参数：

try  
{ if (Page.Request.QueryString\[ " word " ] != null )  
{\_word = Convert.ToString(HttpUtility.UrlDecode(Page.Request.QueryString\[ " word " ],System.Text.Encoding.GetEncoding( " GB2312 " )));}  
}  
catch {\_word = String.Empty;}  
/// 注意编码方式为gb2312，与前面对应

后来，看了孟子E单的文章，才发现有更好的解决方案：  
用Javascript!  
写一个方法放在基类页面中

public void PageLocation( string chineseURL)  
{  
if (chineseURL == null || chineseURL.Trim().Length == 0 )  
{ return ; // 还可能不是一个合法的URLTony2007/11/15  
}  
Page.ClientScript.RegisterStartupScript( this .GetType(), " AgronetPageLocationTo " , " &lt;scripttype='text/javascript'language='javascript'&gt;window.location.href=' " + chineseURL + " ';&lt;/script&gt; " );  
}

然后在页面中调用

string strurl = PreUrl + " ?word={0}&sort={1}&check={2} " ;  
strurl = string .Format(strurl, this .txtSearchTxt.Text.Trim(), this .radioSortDesc.SelectedIndex.ToString(),CheckState.ToString());  
PageLocation(strurl);

注意后种方法用了Javasrcipt，实际应用在分页 时需要保持中文参数，最好还是用window.Location.Href方法!

最后，如果一要在javascript与.net后台代码进行对话，可以这样：

&lt; script language ="JavaScript" &gt;  
function GoUrl()  
{  
var Name = " 中文参数 " ;  
location.href = " B.aspx?Name= " + escape(Name);  
}  
&lt;/ script &gt;  
&lt; body onclick ="GoUrl()" &gt;

接收：

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)string Name = Request.QueryString\[ " Name " ];  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) Response.Write(HttpUtility.UrlDecode(Name));

要点是：

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)将传递的中文参数进行编码，在接收时再进行解码。

完。