Problem with hashtag (#) character in httpclient and WCF

50 views Asked by At

I have a problem using httpClient and WCF, in particular when I put a hashtag (#) as input. Here below my code:

for WCF:

[OperationContract]
[WebGet( RequestFormat = WebMessageFormat.Json, UriTemplate = "/GetCase/{*id}" )]
string[] GetCase( string id );

on client:

HttpClientHandler handler = new HttpClientHandler();
handler.UseProxy = false;
HttpClient client = new HttpClient(handler);
string link = string.Format("https://{0}:{1}/", host, port);
Uri url = new Uri(link);
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
client.BaseAddress = new Uri(link);
string serviceName = "Service";
string restPart = "rest";
string method = "GetCase";
string valueToSearch = Uri.EscapeDataString("TEST#12345");
string completeLinkWithMethod = link + serviceName + "/" + restPart + "/" + method;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = await client.GetAsync(completeLinkWithMethod + "/" + valueToSearch);

When I make a call, on client I see that valueToSearch is "TEST%2312345" but when I go on server, id value is "TEST"

Is there a way to pass all the string without it has been truncated?

When I make a call, on client I see that valueToSearch is "TEST%2312345" but when I go on server, id value is "TEST"

Is there a way to pass all the string without it has been truncated?

2

There are 2 answers

0
Kenneth Ito On

As far as I know, most stacks (including .net) do not send the fragment (#) to the server, they are a client only thing.

https://en.wikipedia.org/wiki/URI_fragment#:~:text=When%20an%20agent%20(such%20as,does%20not%20send%20the%20fragment.

To work around this, you'll need to duplicate or move whatever you need from the fragment into something that goes to the server. For instance the query string.

0
Peter Csala On

One way to overcome this limitation is that you perform custom string encoding on both-side. For example:

var encodedHashtag = $"U+{Char.ConvertToUtf32("""#""", 0)}";
var valueToSearch = "TEST#12345".Replace("#", encodedHashtag);

and

var encodedHashtag = $"U+{Char.ConvertToUtf32("""#""", 0)}";
var decodedId = id.Replace(encodedHashtag, "#");

Please bear in mind that if the user enters a case id, which included U+35 then this approach will not work as intended.