How to mimic ASP Server.URLEncode in ASP.NET?

本秂侑毒 提交于 2019-12-14 02:16:44

问题


In ASP:

Server.URLEncode("+&(). -*<>/\|")
' returns %2B%26%28%29%2E+%2D%2A%3C%3E%2F%5C%7C

In ASP.NET

Uri.EscapeDataString("+&(). -*<>/\|")
// returns %2B%26().%20-*%3C%3E%2F%5C%7C

HttpUtility.UrlEncode("+&(). -*<>/\|") 
// returns %2b%26().+-*%3c%3e%2f%5c%7c

Is there any elegant way how to mimic old ASP behavior in ASP.NET?


回答1:


You can use a regular expression to match the characters that you want to convert, and a lambda expression for creating the hex code:

string input = @"+&(). -*<>/\|";
string encoded = Regex.Replace(
  HttpUtility.UrlEncode(input),
  @"[()\.\-*]",
  m => "%" + Convert.ToString((int)m.Captures[0].Value[0], 16)
);



回答2:


You can try using Server.UrlEncode(), which is supported in ASP.Net.



来源:https://stackoverflow.com/questions/2012483/how-to-mimic-asp-server-urlencode-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!