erotavlas
erotavlas

Reputation: 4475

Bad Request when trying to submit long string to Asp.Net Web Api 2 controller method

I want to check if a long string exists in a column in my database. The string contains spaces, special characters and carriage return / line feeds.

My controller looks like this

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

And I called it like this

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

But the response comes back with 'Bad Request'. The request works fine for simple strings what do not contain spaces or any other special characters.

How can I pass a complex long string to my controller?

Upvotes: 1

Views: 1059

Answers (3)

Hien Nguyen
Hien Nguyen

Reputation: 18975

Change the route to this (removed /Value={text} )

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

    }

and change called method to

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

Because URL has limit length you may need update in web.config

<requestLimits maxQueryString="32768"/>

Upvotes: 0

vladimir
vladimir

Reputation: 15188

Should be used WebUtility.UrlEncode instead of WebUtility.HtmlEncode.

Upvotes: 1

Rahul
Rahul

Reputation: 77856

First of all your route seems wrong and it should rather be

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

Second be aware that every browser poses restriction on length of URI and thus if your string input is very long I would suggest pass it as body of request rather

Upvotes: 1

Related Questions