首页 > 解决方案 > 有没有办法正确传递包含“?”的字符串 到 .net 核心 web api?

问题描述

给定自动完成输入的问题标题,我有以下操作从我的 API 获取问题模型。该操作适用于不包含问号的标题(例如,你多大了)。但是,如果我给出的标题包含问号(例如,你几岁?),则不会返回模型,因为在此过程中会删除问号。

我尝试HttpUtility.UrlDecode()了方法,但没有运气。

您可以在下面找到我的要求

[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);
}

我希望能够?从我的 API 中得到问题。有没有办法做到这一点?

请注意,在 Swagger 中,API Get 请求运行良好!

标签: c#.net-coreasp.net-core-webapi

解决方案


您需要使用HttpUtility.UrlEncode-not Decode。您希望在?将其发送到 URL 之前将其更改为编码字符。HttpUtility.UrlDecode相反。


推荐阅读