Returning a stream from Swagger generated c# server

27 views
Skip to first unread message

Dombat

unread,
Aug 22, 2017, 5:00:01 AM8/22/17
to Swagger
I put this on Stackoverflow yesterday, but this is probably a better place for it!

Swagger has generated a server from an API with a method like this:

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

If I replace string text = "This could be the contents of a file" with lines of code such as:

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

I get a JsonConvert exception saying "invalid characters" (because the string is the content of the file and not json!) If I try and return a stream (e.g. a fileStream) I get an exception too.


What is the correct way to return a stream from swagger generated code in C#?

Dombat

unread,
Sep 6, 2017, 11:12:42 AM9/6/17
to Swagger
This seemed to work for me


            var stream = new FileStream(@".\Files\test.txt", FileMode.Open, FileAccess.Read);
            var reader = new StreamReader(stream, Encoding.ASCII, true);
           
            return new ObjectResult(reader.BaseStream);
Reply all
Reply to author
Forward
0 new messages