[英]Is there a way to pass properly a string containing a “?” to .net core web api?
I have the following action that gets a Question model from my API given the Question title from an autocomplete input. 我有以下操作,可以从我的API中获取问题模型,该问题模型来自自动完成输入,给出了问题标题。 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 . 我尝试了
HttpUtility.UrlDecode()
方法,但是没有运气。
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. 从我的API。 Is there a way to achieve this?
有没有办法做到这一点?
Note that in Swagger, the API Get request is working fine! 请注意,在Swagger中,API Get请求工作正常!
You need to use HttpUtility.UrlEncode
- not Decode
. 您需要使用
HttpUtility.UrlEncode
而非Decode
。 You want to change the ?
您要更改
?
into an encoded character before sending it in the URL. 编码后的字符,然后再通过URL发送。
HttpUtility.UrlDecode
does the opposite. HttpUtility.UrlDecode
则相反。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.