2017-09-27 1 views
4

を取得し、私は私のコントローラでは、このようなポストの方法があります:私は身体の文字列で闊歩/郵便配達を経由してポストをやっているとき"test"その作業を投稿はヌル

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

をfineとdirectoryPathはテスト文字列を取得しましたが、私がこのようなパスをポストしているときには:"C:\Users\futerm\Downloads\test"私はdirectoryPathに入っています。

なぜ私はswaggerの中にパスiで投稿できませんか?

答えて

3

Content-Type: application/jsonでリクエストしているため、本文の文字列がJSON文字列として処理されています。 JSON文字列は二重引用符で囲む必要があり、特殊文字は\文字(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(); 
    } 
} 

拡張メソッドの上には主にAccepting Raw Request Body Content記事から取られています。