简体   繁体   中英

server.htmlencode of asp.net equivalent in asp.net mvc

I have a ASP.NET MVC controller which is making call to another service using HttpClient class.

             var url = "some url";
             var client = new HttpClient();
             var result= client.GetAsync(url);

The URL I am sending contains some special characters. How can encode special characters in ASP.NET MVC controller?

Thanks!!1

尝试这个:

url = HttpUtility.UrlEncode(url);

As you are considering a URL that will be used as such for a request (with HttpClient.getAsync ) -- not as an argument within another URL -- you should use Uri.EscapeUriString .

Here is a comparison of three methods for the following URL:

var url = "http://some url?data=x y+z&user=1#ok";

HttpUtility.UrlEncode

Console.WriteLine(HttpUtility.UrlEncode(url));

http%3a%2f%2fsome+url%3fdata%3dx+y%2bz%26user%3d1%23ok

Obviously, this is not desired: the URL got damaged with / escaped, a + entered in the path, ...etc. The method seems useful for the query part of the URL, but not for the whole lot.

HttpUtility.UrlPathEncode

Console.WriteLine(HttpUtility.UrlPathEncode(url));

http://some%20url?data=x y+z&user=1#ok

This looks useful, although the space is a bit of a problem in the query part (notice the broken hyperlinking here, although browser can deal with it). But more importantly, the method is being deprecated:

Do not use; intended only for browser compatibility. Use UrlEncode .

Uri.EscapeUriString

Console.WriteLine(Uri.EscapeUriString(url));

http://some%20url?data=x%20y+z&user=1#ok

This seems to do the job well: %20 is an escape sequence that all modern browsers should support, also when occurring in the query part of the URL.

There is no need it encoding in Razor View Engine starting from 3rd version, and it's very convenient. Instead if you want to use tags you should use:

@Html.Raw(myString)

So basically just using Razor comes with encoding by default.

You should use HttpUtility.UrlPathEncode

When you use url = HttpUtility.UrlEncode(url) it doesn't work fine with spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM