通过 swagger/postman 获取 null 作为字符串发布到 Web api 路径

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

我的控制器中有一个 post 方法,如下所示:

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

当我通过 swagger/postman 使用正文字符串 "test" 执行 post 时,它工作正常并且 directoryPath 得到了测试字符串但是当我 post 设置路径时像这样:"C:\Users\futerm\Downloads\test" 我进入了 directoryPath null。

为什么我不能 post 路径 i inside swagger?

您使用 Content-Type: application/json 请求,因此正文中的字符串被处理为 JSON 字符串。 JSON 字符串必须用双引号引起来,特殊字符应使用 \ 字符 (specification).

进行转义

所以你应该 post 路径为 "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();
    }
}

以上扩展方法主要摘自Accepting Raw Request Body Content一文