Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
The following code show to you how you could write the encode and decode methods.
The call of the GET endpoint should look like something like this.
using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = baseUrl;
                Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer")));
                response.Wait();
                response.Result.EnsureSuccessStatusCode();
            }
The following code show to you how you could write the encode and decode methods.
public class EncoderHelper
{
    public static string Encode(string content)
    {
        byte[] encodedBytes = UTF8Encoding.UTF8.GetBytes(content);
        string externalIdEncoded = HttpServerUtility.UrlTokenEncode(encodedBytes);
        return externalIdEncoded;
    }
    public static string Decode(string content)
    {
            var decodedBytes = HttpServerUtility.UrlTokenDecode(content);
        string externalId = UTF8Encoding.UTF8.GetString(decodedBytes);
        return externalId;
    }
}
The call of the GET endpoint should look like something like this.
using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = baseUrl;
                Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", EncoderHelper.Encode("qwert/qwerqwer"))));
                response.Wait();
                response.Result.EnsureSuccessStatusCode();
            } 
Also, don't forget that you would need to use the Decode method on the other end.

Why not WebUtility.UrlEncode ?
ReplyDelete(or HttpUtility.UrlEncode if a dependency to System.Web it's ok)
Give it a try and see what is happening when you have "\" and "/" on the server side (in the APIController).
DeleteStrange - when the server receives a percent-encoded / (%2F) in the URI, it should not interpret it as a path separator and use it for routing..
DeleteYou are right, and there seems to be a setting for that in .NET: http://msdn.microsoft.com/en-us/library/ee656542(v=vs.110).aspx : genericUriParserOptions="DontUnescapePathDotsAndSlashes"
Delete