请问C#有一个等同于JavaScript的EN codeURIComponent()? [英] Does C# have an equivalent to JavaScript's encodeURIComponent()?

查看:135
本文介绍了请问C#有一个等同于JavaScript的EN codeURIComponent()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript的:

 连接codeURIComponent(©√​​)==%C2%A9%E2%88%9A
 

是否有一个相当于C#应用程序?转义HTML字符我使用的:

  txtOut.Text = Regex.Replace(txtIn.Text,@[\ u0080- \ uFFFF],
    M => @与&#+((int)的m.Value [0])的ToString()+;);
 

但我不知道如何在比赛转换为JS使用正确的十六进制格式。例如,这code:

  txtOut.Text = Regex.Replace(txtIn.Text,@[\ u0080- \ uFFFF],
M => @%+的String.Format({0:X},((int)的m.Value [0])));
 

返回%A9%221A©√而不是 %C2%A9%E2%88%9A。它看起来像我需要了分割字符串为字节或东西。

编辑:这是一个Windows应用程序,在的System.Web 唯一可用的项目有:性AspNetHostingPermission AspNetHostingPermissionAttribute AspNetHostingPermissionLevel

解决方案

技术上,并经常在实践中,向上投答案是不正确的。

Uri.EscapeUriString HttpUtility.UrlPathEn code 是逃避意味着一个字符串的正确方法是一个URL的一部分。

举个例子字符串堆栈溢出

  • HttpUtility.UrlEn code(堆栈溢出) - > 堆栈溢出+

  • Uri.EscapeUriString(堆栈溢出) - > 堆栈%20Overflow

  • Uri.EscapeDataString(堆栈溢出+) - >同时连接codeS +到% 2B ----> 堆叠%20%2B%20%20Overflow

作为URL的一部分,实际使用时(而不是查询字符串参数之一的值)

只有<打击>后者最后是正确的

In JavaScript:

encodeURIComponent("©√") == "%C2%A9%E2%88%9A"

Is there an equivalent for C# applications? For escaping HTML characters I used:

txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]",
    m => @"&#" + ((int)m.Value[0]).ToString() + ";");

But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:

txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]",
	m => @"%" + String.Format("{0:x}", ((int)m.Value[0])));

Returns "%a9%221a" for "©√" instead of "%C2%A9%E2%88%9A". It looks like I need to split the string up into bytes or something.

Edit: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.

解决方案

Technically, and often in practice, the up-voted answer is not correct.

Uri.EscapeUriString or HttpUtility.UrlPathEncode is the correct way to escape a string meant to be part of a URL.

Take for example the string "Stack Overflow":

  • HttpUtility.UrlEncode("Stack Overflow") --> "Stack+Overflow"

  • Uri.EscapeUriString("Stack Overflow") --> "Stack%20Overflow"

  • Uri.EscapeDataString("Stack + Overflow") --> Also encodes "+" to "%2b" ---->Stack%20%2B%20%20Overflow

Only the latter last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)

这篇关于请问C#有一个等同于JavaScript的EN codeURIComponent()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆