0

I have the following action that gets a Question model from my API given the Question title from an autocomplete input. The action is working fine with titles that do not contain a question mark (Ex. How old are you). But if I give a title containing a question mark (Ex. How old are you?) the model is not returned as the question mark is being removed in the process.

I tried HttpUtility.UrlDecode() method but with no luck .

Below you can find my requests

[HttpGet]
public async Task<IActionResult> GetQuestionAsync(string question) {
    Questions q = new Questions();
    HttpClient client = _api.Initial();
    HttpResponseMessage res = await client.GetAsync("api/Search/" + question);
    if (res.IsSuccessStatusCode) {
        var result = res.Content.ReadAsStringAsync().Result;
        q = JsonConvert.DeserializeObject<Questions>(result);
    }
    return View(q);
}

[Produces("application/json")]
[HttpGet]
[Route("{keyword}")]
public async Task<IActionResult> GetByString([FromRoute(Name = "keyword")] string keyword) {
    if (!ModelState.IsValid) {
        return BadRequest(ModelState);
    }
    var question = await _context.Questions
        .SingleOrDefaultAsync(m => m.Question == HttpUtility
            .UrlDecode(keyword.ToString()));

    if (question == null) {
        return NotFound();
    }
    return Ok(question);
}

I expect to be able to get questions including ? from my API. Is there a way to achieve this?

Note that in Swagger, the API Get request is working fine!

1 Answer 1

1

You need to use HttpUtility.UrlEncode - not Decode. You want to change the ? into an encoded character before sending it in the URL. HttpUtility.UrlDecode does the opposite.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reply ! I tried it but now although i can get question with "?" (ex. how?) i cannot get questions with spaces (ex. how are you?)
A more complete solution exists in Uri.EscapeDataString, which should cover both spaces and things like ?. However, spaces are just %20, so you could also just do .Replace(" ", "%20").
I also tried .Replace no luck ....I will check EscapeDataString and get back to you ! Thanks again for the reply !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.