I've written a http service using HttpListener.
The service receives GET requests, with a single query string variable req that holds all parameters in a json-encoded string, then performs some tasks.
The requests are generated from other servers and query strings are url-encoded using UTF-8.
The problem is that the Request object from the HttpListenerContext instance is decoding the query string using Encoding.Default rather than UTF-8.
For example, if I send this request to the server:
http://myserver/?req={"name":"Micciché"}
which is properly encoded to this url before being sent:
http://myserver/?req=%7B%22name%22%3A%22Miccich%C3%A9%22%7D
(note that the é character correctly becomes %C3%A9 in UTF-8)
when I receive the request on my server and try to read and parse the req variable with this code:
string jsonreq = context.Request.QueryString["req"] ?? "";
MyRequest reqObj = JsonConvert.DeserializeObject<MyRequest> (jsonString);
the wrong encoding is applied and the string "Micciché" becomes "Micciché"
I've looked for a way to enforce UTF-8 decoding but so far I've found nothing.
Browsing HttpListenerRequest class source code on Microsoft GitHub Reference Source, it seems that the applied encoding is extracted from Content-Type request header only if there is a body in the request, which is not my case.
So far the only quick & dirty solution I've found is to manually reparse the raw querystring using HttpUtility.UrlDecode which comes from the System.Web namespace which I'd rather avoid:
NameValueCollection qs = HttpUtility.ParseQueryString(context.Request.Url.Query, Encoding.UTF8);
string jsonreq = qs["req"] ?? "";
MyRequest reqObj = JsonConvert.DeserializeObject<MyRequest> (jsonString);
Furthermore, I would like to avoid also the burden of double parsing of the query string (one internal from HttpListenerRequest and one from my code).
How can I force HttpListenerRequest to always decode query strings using UTF-8?