从Swagger返回一个流生成的c#server

时间:2017-08-21 14:59:09

标签: c# json asp.net-web-api stream swagger

Swagger使用以下方法从API生成服务器:

[HttpGet]
    [Route("SomeRoute")]
    [SwaggerOperation("GetFile")]
    [SwaggerResponse(200, type: typeof(System.IO.Stream))]
    public virtual IActionResult GetFile()
    {
        string exampleJson = null;
        string text = "This could be the contents of a file";

        exampleJson = text;
        var example = exampleJson != null
        ? JsonConvert.DeserializeObject<System.IO.Stream>(exampleJson)
        : default(System.IO.Stream);
        return new ObjectResult(example);
    }

如果我替换&#34;这可能是文件的内容&#34;使用代码行,例如:

var stream = new FileStream(@".\Files\test.txt", FileMode.Open, FileAccess.Read);
var requestBody = new StreamReader(stream,Encoding.ASCII,true).ReadToEnd();

我收到一个JsonConvert异常,说&#34;无效字符&#34;。从swagger生成的代码返回流的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

这似乎有效。

    var stream = new FileStream(@".\Files\test.txt", FileMode.Open, FileAccess.Read);
    var reader = new StreamReader(stream, Encoding.ASCII, true);

    return new ObjectResult(reader.BaseStream);