How to handle FileResponse return type of Nswag methods
Asked Answered
W

3

8

I am using Nswag to generate client library to consume an API created from .NET Core Application. Currently I am using actions that returns IActionResult to benefit from methods such as return NotFound(); and return Ok(objectValue); If the return type is IActionresult generated Csharp Client methods from Nswag have return type of FileResponse.

If I change return type to a certain class then the same return type is returned from the generated methods. This will prevent to use the benefits that I mentioned before.

Usually the return type is from a known return type and never return an anonymous type.

I have managed to get the response from reading the Stream from FileResponse and converted it to an object with a generic method JsonConvert.DeserializeObject<T>(value); but this seems to be extra work needed to be done.

Is there anything I am missing to handle FileResponse return type? Is it better to change from IActionResult to a known object?

Wedekind answered 19/12, 2019 at 10:31 Comment(0)
W
3

I managed to solve the problem by changing actions to return ActionResult<ObjectType> instead of IActionResult. For more detail look at this answer.

Wedekind answered 20/1, 2020 at 9:58 Comment(0)
G
0

NSwag client generator requires additional annotations to generate accurate client code. FileResponse is returned for IActionResult - as you stated. If action returns more codes then ProducesResponseType helps.

Example using IActionResult (string is returned):

[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpPost("foo")]
public IActionResult FooAction([FromBody] string param)

Example using ActionResult<>:

[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpPost("foo")]
public ActionResult<string> FooAction([FromBody] string param)

Need to know that ASP .NET Core uses ProblemDetails (it's configurable) for error codes generated using build-in parameterless methods. If those methods are called with parameter, then ProducesResponseType will require to add type - without it wrong code will be generated.

Gearhart answered 15/11, 2020 at 4:8 Comment(0)
R
0

You can do one of the following:

  • Change the return type (e.g.: Instead of IActionResult use FileStreamResult)

  • Use the below code to get the file in SwaggerUI:

    public async Task<Stream> GetTemplateAttachmentAsync(string fileName) 
    {
         //code here to Get the file from AzureBlob or storage 
    }
    
    // calling method 
    var content = GetAsync(fileName, cancellationToken);
    return File(content.Stream, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    
Ravishment answered 22/12, 2022 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.