如何在输入参数中传递加号?

3

出于安全原因,您应该始终进行URL编码。 - Steven Sudit
7个回答

4

2

如果可以的话,请使用Server.UrlEncode方法:

代码后台:

string email = "johnsmith+1@gmail.com"
lnkThingy.NavigateUrl = "http://www.website.com/Page1.aspx?email=" + Server.UrlEncode(email);

1
在URL中,加号通常用作空格的占位符。 "domain.com" 在处理该页面之前可能会将其转换回空格。
您需要进行URL转义以使用加号:
 http://domain.com/page1.aspx?username=johnsmith%2b1@gmail.com

'+' 等于 ascii 43 等于 0x2B。URL 转义是 "百分号; 字符的十六进制值"


1

johnsmith%2b1%40gmail.com

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS G:\Users\Max> [reflection.assembly]::loadwithpartialname("System.Web")

GAC    Version        Location
---    -------        --------
True   v2.0.50727     G:\Windows\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll


PS G:\Users\Max> [web.httputility]::UrlEncode("johnsmith+1@gmail.com")
johnsmith%2b1%40gmail.com
PS G:\Users\Max>

1
从来没有想过使用PowerShell来演示这个。很酷 :) - Ronald Wildenberg

1
你应该使用 HttpUtility.UrlEncode 来处理这个问题。它会转义所有在 URL 中可能有其他含义的字符。你的电子邮件地址将会变成这样:
johnsmith%2b1%40gmail.com

加号(+)和艾特符号(@)都使用十六进制表示法进行转义,前面加上百分号(%)。您可以在这里www.asciitable.com)自行验证。


0

加号在调用 UrlDecode 方法之前,往往被 .NET 解码为空格字符。 我使用以下字符串扩展方法来纠正此问题,并提供更好的访问和控制查询字符串参数的方式。

    /// <summary>
    /// Character Encodes a (string).  Specifically used for Querystring parameters.
    /// </summary>
    /// <remarks></remarks>
    /// <param name="String"></param>
    /// <returns>string</returns>
    public static string EncodeForQueryString(this string String)
    {
        String = System.Web.HttpUtility.UrlEncode(String);
        return String;
    }

    /// <summary>
    /// Character Decodes a (string).  Specifically used for Querystring parameters.
    /// </summary>
    /// <remarks>The plus sign causes issues when using System.Web.HttpUtility.UrlDeEncode.  The plus sign is often decoded before it reaches this method.  This method will replace any extra + with %2b before attempting to decode</remarks>
    /// <param name="String"></param>
    /// <returns>string</returns>
    public static string DecodeForQueryString(this string String)
    {
        String = String.Replace("+", "%2b");
        String = System.Web.HttpUtility.UrlDecode(String);
        return String;
    }

为了创建您的查询字符串参数值的编码字符串:

string myUrl = "myPage.htm?q=" + "Saving+Silverman".ToString().EncodeForQueryString();

要获取并解码查询字符串参数的值:

string myDecodedString = Request.Params["q"].DecodeForQueryString();

0

加号(+)在查询字符串中具有语义意义。它用于表示空格。大多数服务器端脚本在使用查询参数之前会对其进行解码,以便将+正确转换为空格。

因此,在发送查询字符串中的值之前,请使用%2B将+符号转换,并随后发送。以下是示例代码。

protected void btnRedirect_Click(object sender, EventArgs e)
{
    string signature="f1wRcMvJJ2YjLjc8dc+7ykY9szg=&kanna";
    signature = signature.Replace("+", "%2B");
    Response.Redirect("Encode-Decode-QueryString.aspx?sign=" +     Server.UrlEncode(signature));
}

您可以参考下面的链接获取更多详细信息

http://www.dotnetpickles.com/2014/02/aspnet-how-to-pass-plus-in-query-string.html

谢谢


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接