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

I have a mail method in the controller:

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 make a message through swagger / postman with the string body "test", its work is fine, and directoryPath got the test string, but when I send this way: "C:\Users\futerm\Downloads\test"I got null in the path directory.

Why can't I send messages using the path I have inside the swagger?

+4
source share
1 answer

You are querying with Content-Type: application/json, and so the string in the body is treated as a JSON string. The JSON string must be double and special characters must be escaped using the character \( specification ).

, "C:\\Users\\futerm\\Downloads\\test".


, Content-Type: text/plain. , .

.

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

:

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

, , , .

+3

Source: https://habr.com/ru/post/1686458/


All Articles