尝试向Asp.Net Web Api 2控制器方法提交长字符串时出现错误请求

时间:2019-04-30 21:37:41

标签: c# asp.net-web-api

我想检查数据库中的列中是否存在长字符串。该字符串包含空格,特殊字符和回车符/换行符。

我的控制器看起来像这样

    [ResponseType(typeof(ReportsDTO.ReportDTO))]
    [Route("api/Reports/GetReportIfExists/Value={text}")]
    public IHttpActionResult GetReportIfExists(string text)
    {
        Report report = db.Reports.Where(x => x.reporttext == text).First();

        if (report == null)
        {
            return NotFound();
        }

        ReportsDTO.ReportDTO reportDTO = TranslateDTO.ConvertReportToDTO(report);

        return Ok(reportDTO);
    }

我这样称呼它

    static async Task<string> GetReportAsync(string reporttext)
    {
        string responseString = string.Empty;

        var builder = new UriBuilder("http://localhost/myAPI/api/Reports/GetReportIfExists/Value=" + WebUtility.HtmlEncode(reporttext));
        builder.Port = -1;

        string url = builder.ToString();

        var response = client.GetAsync(url).Result;
        if (response.IsSuccessStatusCode)
        {
            responseString = response.Content.ReadAsStringAsync().Result;
        }

        return responseString;
    }

但响应返回“错误请求”。 对于不包含空格或任何其他特殊字符的简单字符串,该请求可以正常工作。

如何将复杂的长字符串传递给控制器​​?

3 个答案:

答案 0 :(得分:1)

首先,您的路线似乎有误,应该是

[Route("api/Reports/GetReportIfExists/{text}")]

第二,请注意,每个浏览器都会对URI的长度进行限制,因此,如果您的字符串输入很长,我建议将其作为请求正文传递

答案 1 :(得分:1)

应使用WebUtility.UrlEncode代替 WebUtility.HtmlEncode

答案 2 :(得分:0)

将路由更改为此(已删除/ Value = {text})

 [ResponseType(typeof(ReportsDTO.ReportDTO))]
    [Route("api/Reports/GetReportIfExists")]
    public IHttpActionResult GetReportIfExists(string text)
    {

    }

并将调用的方法更改为

 var builder = new UriBuilder("http://localhost/myAPI/api/Reports/GetReportIfExists?text=" + WebUtility.HtmlEncode(reporttext));

由于URL的长度限制,您可能需要在web.config中进行更新

<requestLimits maxQueryString="32768"/>
相关问题