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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.