开发者

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

开发者 https://www.devze.com 2022-12-15 09:40 出处:网络
In ASP: Server.URLEncode(\"+&(). -*<>/\\|\") \' returns %2B%26%28%29%2E+%2D%2A%3C%3E%2F%5C%7C

In ASP:

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

In ASP.NET

Uri.EscapeDataString("+&a开发者_StackOverflow中文版mp;(). -*<>/\|")
// 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?


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)
);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号