RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.74k stars 1.29k forks source link

Web API -> TS client generation with custom media type formatters #890

Open grovesNL opened 7 years ago

grovesNL commented 7 years ago

I've been playing around with various methods to handle file uploading in Web API lately and was wondering how to handle custom media type formatters. I mentioned it briefly in Gitter but wanted to post some thoughts here in case somebody else has hit this problem.

Consider a case as discussed in http://blog.marcinbudny.com/2014/02/sending-binary-data-along-with-rest-api.html

Binary data is sent to the Web API, yet the signature in Web API is simply:

[Route("api/send")]
public string UploadImageSet(ImageSet model)

This is because ImageSet is created from a custom media type formatter (ImageSetMediaTypeFormatter) as explained in the post. So it's similar to passing HttpPostedFileBase or IFormFile and reading it into a DTO in the controller method. Instead a media type formatter is registered to separate this concern from the method to achieve the same result.

I don't know whether this is a good idea yet. However it does raise a question: how can I specify that the client generation still treats the method as if it still used HttpPostedFileBase or IFormFile as the argument?

Some ideas:

grovesNL commented 7 years ago

I have a temporary workaround for form data. I created an empty interface with the name IFormFile (I know this isn't a good idea) and the DTO implements it (i.e. ImageSet : IFormFile). Now the client generation is correct without changing the signature of the controller method.

RicoSuter commented 7 years ago

Maybe we could add a way to specify other types besides HttpPostedFileBase or IFormFile that we know will be handled by a custom media type formatter.

I think we should support a SwaggerFileParameterAttribute on the action method parameter and class.

Perhaps there could be a way to easily override the method signature that the client generator uses? This could be useful for other cases than form data. Maybe this already exists?

Sorry, I don't understand what you meant with this?

You can always write a custom operation processor and modify the produced swagger...

grovesNL commented 7 years ago

I think we should support a SwaggerFileParameterAttribute on the action method parameter and class.

That could be a good solution.

I was thinking more general like [RequestType(typeof(int), typeof(HttpPostedFileBase)], where this signature is used for the operation processor instead of the method signature (i.e. UploadImageSet(int id, ImageSet model)).

You can always write a custom operation processor and modify the produced swagger...

Thanks, I didn't know about custom operation processor. That sounds it would work too.