URL 对 C# 中的所有非字母数字进行编码

发布于 2024-09-05 21:45:24 字数 853 浏览 5 评论 0原文

我需要对电子邮件地址进行完全 URL 编码。

HttpUtility.UrlEncode 似乎忽略某些字符,例如!和 。

我需要在格式如下的 url 中传递电子邮件地址:

/Users/[email protected]/Comments

因为我的 WebMethod uri 模板如下所示:

[WebGet(UriTemplate = "Users/{emailAddress}/Comments")]

句点会中断 WCF,并且不会将电子邮件地址传递给我的 REST Web 服务方法。 删除句点就可以很好地传递该值。我希望有一种方法可以对所有非字母数字字符进行编码,因为使用该服务的所有内容都需要这样做。

编辑

我曾考虑使用:

Convert.ToBase64String(Encoding.ASCII.GetBytes("[email protected]"))

大多数其他语言都有简单的方法将字符串转换为base64吗?我主要担心的是,使用此服务的客户将需要使用 Java、PHP、Ruby 等对电子邮件地址进行编码。

I need to fully URL Encode an email address.

HttpUtility.UrlEncode seems to ignore certain characters such as ! and .

I need to pass an email address in a url formated like this:

/Users/[email protected]/Comments

Because my WebMethod uri template looks like this:

[WebGet(UriTemplate = "Users/{emailAddress}/Comments")]

The period breaks WCF and will not pass the email address to my REST webservice method.
Removing the period passes the value just fine. I'm hoping there is a method which will encode all non alpha numeric characters since everything consuming this service will need to do this.

EDIT

I had considered using:

Convert.ToBase64String(Encoding.ASCII.GetBytes("[email protected]"))

Do most other languages have easy ways to convert a string to base64? My main concern is that our customers who consume this service will need to encode the email address using Java, PHP, Ruby, etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

阳光下的泡沫是彩色的 2024-09-12 21:45:24

这是您可以用来完成编码的潜在正则表达式。

Regex.Replace(s, @"[^\w]", m => "%" + ((int)m.Value[0]).ToString("X2"));

我不确定是否存在定义的现有框架方法来严格编码您可以向客户指出的所有非字母数字字符。

Here's a potential Regex you could use to accomplish the encoding.

Regex.Replace(s, @"[^\w]", m => "%" + ((int)m.Value[0]).ToString("X2"));

I'm not sure that there is an existing framework method defined to strictly encode all non-alphanumeric characters that you could point your clients to.

汐鸠 2024-09-12 21:45:24

使用十六进制。有一个 ConvertTo 和一个 From 以及一个示例测试...

您还可以使用正则表达式将不匹配 A 到 Z 的字符转义,这样您的 URL 看起来仍然很漂亮。

它将返回一大串数字,所以你应该很好

        public static string ConvertToHex(string asciiString)
    {
        var hex = "";
        foreach (var c in asciiString)
        {
            int tmp = c;
            hex += String.Format("{0:x2}", Convert.ToUInt32(tmp.ToString()));
        }
        return hex;
    }

    public static string ConvertToString(string hex)
    {
        var stringValue = "";
        // While there's still something to convert in the hex string
        while (hex.Length > 0)
        {
            stringValue += Convert.ToChar(Convert.ToUInt32(hex.Substring(0, 2), 16)).ToString();
            // Remove from the hex object the converted value
            hex = hex.Substring(2, hex.Length - 2);
        }

        return stringValue;
    }

    static void Main(string[] args)
    {
        string hex = ConvertToHex("[email protected]");
        Console.WriteLine(hex);
        Console.ReadLine();
        string stringValue =
        ConvertToString(hex);
        Console.WriteLine(stringValue);
        Console.ReadLine();

    }

Use hex. There is a ConvertTo and a From and a sample test...

You can also just scape the characters that don't match A to Z by using a regex so your URL still looks pretty.

It will return a big list of numbers so you should be good

        public static string ConvertToHex(string asciiString)
    {
        var hex = "";
        foreach (var c in asciiString)
        {
            int tmp = c;
            hex += String.Format("{0:x2}", Convert.ToUInt32(tmp.ToString()));
        }
        return hex;
    }

    public static string ConvertToString(string hex)
    {
        var stringValue = "";
        // While there's still something to convert in the hex string
        while (hex.Length > 0)
        {
            stringValue += Convert.ToChar(Convert.ToUInt32(hex.Substring(0, 2), 16)).ToString();
            // Remove from the hex object the converted value
            hex = hex.Substring(2, hex.Length - 2);
        }

        return stringValue;
    }

    static void Main(string[] args)
    {
        string hex = ConvertToHex("[email protected]");
        Console.WriteLine(hex);
        Console.ReadLine();
        string stringValue =
        ConvertToString(hex);
        Console.WriteLine(stringValue);
        Console.ReadLine();

    }
信愁 2024-09-12 21:45:24

除非我弄错了,否则 URL 编码只是百分号后跟 ASCII 数字(十六进制),所以这应该有效...

Dim Encoded as New StringBuilder()

For Each Ch as Char In "[email protected]"
    If Char.IsLetterOrDigit(Ch)
         Encoded.Append(Ch)
    Else
         Encoded.Append("%")
         Dim Byt as Byte = Encoding.ASCII.GetBytes(Ch)(0)
         Encoded.AppendFormat("{0:x2}", Byt)
    End If
Next

上面的代码结果为 something%2Bme%40example.com

Unless I am mistaken, URL Encoding is simply the percent sign followed by the ASCII number (in hex), so this should work...

Dim Encoded as New StringBuilder()

For Each Ch as Char In "[email protected]"
    If Char.IsLetterOrDigit(Ch)
         Encoded.Append(Ch)
    Else
         Encoded.Append("%")
         Dim Byt as Byte = Encoding.ASCII.GetBytes(Ch)(0)
         Encoded.AppendFormat("{0:x2}", Byt)
    End If
Next

The above code results in something%2Bme%40example.com

戏蝶舞 2024-09-12 21:45:24

我发现了这个问题的解决方案。

.Net 4.0实际上已经解决了URI模板中特殊字符的问题。

这条线索为我指明了正确的方向。 http://social.msdn。 microsoft.com/Forums/en/dataservices/thread/b5a14fc9-3975-4a7f-bdaa-b97b8f26212b

我添加了所有配置设置并且它起作用了。但请注意,它仅适用于带有 .Net 4.0 的真实 IIS 设置。我似乎无法让它与 Visual Studio Dev IIS 一起使用。

更新 - 实际上,我尝试删除这些配置设置,它仍然有效。也许.Net 4.0已经默认修复了这个问题。

I've discovered a solution to this issue.

.Net 4.0 has actually fixed the problem with special characters in the URI Template.

This thread pointed me in the right direction. http://social.msdn.microsoft.com/Forums/en/dataservices/thread/b5a14fc9-3975-4a7f-bdaa-b97b8f26212b

I added all the config settings and it worked. But note, it ONLY works with a REAL IIS setup with .Net 4.0. I can't seem to get it to work with the Visual Studio Dev IIS.

Update - Actually, I tried removing those config settings and it still works. It maybe be that .Net 4.0 has fixed this problem by default.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文