Posting to web api path as a string via swagger/postman getting null

Viewed 538

I have in my controller a post method like this:

public IActionResult Post([FromBody]string directoryPath)
{
      _log.Debug($"Got ScanDirectory request for directoryPath:{directoryPath}");
      if (string.IsNullOrEmpty(directoryPath))
      {
          return NotFound("DirectoryPath is empty");
      }
 }

when I am doing post via swagger/postman with body string "test" its working fine and directoryPath got the test string but when i'm posting a path like this: "C:\Users\futerm\Downloads\test" i got in directoryPath null.

Why i can't post with path i inside swagger?

1 Answers

You do request with Content-Type: application/json and so the string in body is processing as a JSON string. And a JSON string must be double-quoted and special characters should be escaped using \ character (specification).

So you should post path as "C:\\Users\\futerm\\Downloads\\test".


If you don't want to do characters escaping, then consider doing a request with Content-Type: text/plain. But then you need to modify your code to read directly from the request body.

Controller action.

    [HttpPost]
    public async Task<IActionResult> Post()
    {
        var directoryPath = await Request.GetRawBodyStringAsync();
        //_log.Debug($"Got ScanDirectory request for directoryPath:{directoryPath}");
        if (string.IsNullOrEmpty(directoryPath))
        {
            return NotFound("DirectoryPath is empty");
        }

        return Ok(directoryPath);
    }

Helper method:

public static class HttpRequestExtensions
{

    /// <summary>
    /// Retrieve the raw body as a string from the Request.Body stream
    /// </summary>
    /// <param name="request">Request instance to apply to</param>
    /// <param name="encoding">Optional - Encoding, defaults to UTF8</param>
    /// <returns></returns>
    public static async Task<string> GetRawBodyStringAsync(this Microsoft.AspNetCore.Http.HttpRequest request, System.Text.Encoding encoding = null)
    {
        if (encoding == null)
            encoding = System.Text.Encoding.UTF8;

        using (var reader = new System.IO.StreamReader(request.Body, encoding))
            return await reader.ReadToEndAsync();
    }
}

Above extension method is mainly taken from Accepting Raw Request Body Content article.

Related