Http.Page.Request [“”]没有返回正确的值

时间:2013-03-13 14:06:08

标签: asp.net request

的情况: - 有一个Home.aspx页面,可以由唯一用户打开(“userName”变量)。

此页面有一个弹出窗口控件名称'alertWindow'。

在Home.aspx.cs的pageLoad事件中,使用NavigateUrl属性在'alertWindow'中打开Welcome.aspx页面。

传递给Welcome.aspx页面的查询字符串包含参数“UserName”,此参数设置为登录用户的名称(“userName”变量)。

现在,当代码执行到Welcome.aspx.cs页面时,“Request [”UserName“]”用于获取\检索查询字符串中存在的当前“userName”参数。

问题: - 当登录用户的名称包含空格或其他非常用字符时,则“Request [”UserName“]。ToString()”不检索实际和正确的值。

对于Ex。如果登录“userName”=“A& T Telecom”,则“Request [”UserName“]。ToString()仅检索”A“而不检索任何其他内容。

但是如果userName字符串是一个像“micheal”这样的正确值,那么“Request [”UserName“]。ToString()只能正确检索”Micheal“

要求: - 请提供一种方法,以便我从Request [“UserName”]获取任何类型的“userName”字符串值的正确值。

Home.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (user is valid)
       alertWindow.NavigateUrl = "Welcome.aspx?userName=" + currentUser.ToString();
}

Welcome.aspx.cs : -

currentUserName = Request["userName"].ToString();

2 个答案:

答案 0 :(得分:3)

这是合乎逻辑的,因为你没有Encode your url。试试这个:

alertWindow.NavigateUrl = "Welcome.aspx?userName=" + Server.UrlEncode(currentUser.ToString());

再说几句,它们是URL上使用的一些特殊字符,如

: / # ? & @ % + (and the space)

所有这些字符必须编码为不同的格式,因此网址不会破坏,UrlEncode就是这样。

两个音符。

  1. 我选择Server来调用UrlEncode,因为它不依赖于Request,你可以在一个线程中使用它,也可以在任何未从Page调用的函数中使用它。
  2. 使用时Request.QueryString制作UrlDecode。要获取编码网址,请调用Request.RawUrl

答案 1 :(得分:1)

您无法在网址中添加空格,因此需要编码:

//uses HttpUtility.UrlEncode internally

Server.UrlEncode("something with spaces");

HttpUtility.UrlEncode("something with spaces");