NSwag: NSwag generate wrong code for FileContentResult type.
Hi Team,
I have Web.API core action method which returns FileContentResult, code example:
return new FileContentResult(fileViewModel.Content, fileViewModel.FileMetadataViewModel.MimeType)
{
FileDownloadName = fileViewModel.FileMetadataViewModel.FileName
};
It generates code like:
var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(FileContentResult);
try
{
result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<FileContentResult>(responseData_);
return result_;
}
catch (System.Exception exception)
{
throw new BusinessApiException("Could not deserialize the response body.", status_, result_.ToString(), headers_, exception);
}
Which cause SerializationException.
My manual fix looks like:
var result_ = new FileContentResult();
// Get file's byte array
byte[] responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
// Set FileContentResult properties manually
result_.ContentType = headers_["Content-Type"].FirstOrDefault();
result_.FileDownloadName = headers_["Content-Disposition"].FirstOrDefault();
result_.FileContents = responseData_;
try
{
return result_;
}
catch (System.Exception exception)
{
throw new BusinessApiException("Could not deserialize the response body.", status_, result_.ToString(), headers_, exception);
}
Could you please help me or/and suggest how to fix it. (Probably, I’m using wrong type or doing something wrong etc)
Thanks a lot in advance !!
About this issue
- Original URL
- State: open
- Created 7 years ago
- Reactions: 5
- Comments: 49 (24 by maintainers)
Ok, just tried this with the latest master version. This operation
gives me this swagger:
and this client code:
so it looks good to me…
Ok,
So, If I set [ProducesResponseType(typeof(FileResult), 200)] in the service, the NSwag returns a FileResult instead of a FileResponse which contains a Stream property.
If I set a [ProducesResponseType(typeof(byte[]), 200)], then NSwag generates the FileResponse class.
instead of typeof(byte[]) use one of these types to specify a file response:
Not sure if I fully grasp the problems OP is experiencing, but here’s my take on it.
[SwaggerResponse(typeof(byte[]))]is not correct, since it generatesstringforschema.type. Instead, simply usingIHttpActionResultor any other type listed inIsFileResponsemakes it work.I don’t think you can simply add
byte[]toIsFileResponseeither, because (I assume) it’s technically possible to have a a byte array represented by JSON? Anyway, the problem really is that Web API doesn’t come with a built-in type for file responses that implementsIHttpActionResult, you need to roll your own. If it did, everyone could use the same type and it could be added toIsFileResponse.Thanks for the answer.
Method with signature: