0

Hi all enthusiastics programmers. I am making a get call from a C# client towards a web-api Project The code looks like below

 private const string Url = "http://localhost:61809/"; public ItemService() { _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } public async Task<IEnumerable<Item>> GetItemsAsync(string searchString) { List<Items> = null; string path = @"api/item/" + searchString; HttpResponseMessage response = await _httpClient.GetAsync(Url+path).ConfigureAwait(false); if (response.IsSuccessStatusCode) { items = await response.Content.ReadAsAsync<List<Item>>().ConfigureAwait(false); } return items; } 

Everything works but if a look after a item whcih contains the character # it fails. If i looks for the item i.e Mastering C# it fails. I have debugged this on the backend side also and the content on the backend doesn't contain the character #. The content is Mastering C which of course fails. The same occurs if i sent the request from Postman What can i do to get it works? Some special encoding or configuration of the backend code?

1
  • try using System.Web.HttpUtility.UrlEncode(path) Commented Mar 31, 2017 at 12:32

1 Answer 1

1

Yes, you do need to encode it. I'm in the process of writing a library that does this correctly, but it's not released yet.

In the meantime, you can use percent encoding as such:

public class UrlEncoding { public static Encoding Utf8EncodingWithoutBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); public static string PercentEncodePathSegment(string value) { var bytes = Utf8EncodingWithoutBom.GetBytes(value); var sb = new StringBuilder(bytes.Length); foreach (var ch in bytes) { if (ch == '-' || ch == '.' || ch == '_' || ch == '~' || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'Z') || ch == '!' || ch == '$' || ch == '&' || ch == '\'' || ch == '(' || ch == ')' || ch == '*' || ch == '+' || ch == ',' || ch == ';' || ch == '=' || ch == ':' || ch == '@') { sb.Append((char)ch); } else { sb.Append("%" + ch.ToString("X2", CultureInfo.InvariantCulture)); } } return sb.ToString(); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.