Git Product home page Git Product logo

swashbuckle.aspnetcore.jsonmultipartformdatasupport's Introduction

https://www.nuget.org/packages/Swashbuckle.AspNetCore.JsonMultipartFormDataSupport https://www.nuget.org/packages/Swashbuckle.AspNetCore.JsonMultipartFormDataSupport

Swashbuckle.AspNetCore.JsonMultipartFormDataSupport

Adds support for json in multipart/form-data requests.

Exmaple

Usage

  1. Simple add this to your ConfigureServices
services.AddJsonMultipartFormDataSupport(JsonSerializerChoice.Newtonsoft);

Or manually:

  • Binder
services
    .AddMvc(
        properties => {
            // ...
            properties.ModelBinderProviders.Insert(0, new FormDataJsonBinderProvider()); // Here
        }
    )
  • Operation filter
services.AddSwaggerGen(c => {
        c.OperationFilter<MultiPartJsonOperationFilter>();
    });
  1. Add to your Controller
[HttpPost]
[Consumes("multipart/form-data")] 
public async Task<IActionResult> Post([FromForm] MultipartFormData<Product> multiPartData) {
    var file = multiPartData.File;
    var product = multiPartData.Json;
}

or

[HttpPost]
[Consumes("multipart/form-data")] 
public async Task<IActionResult> Post([FromForm] MultipartRequiredFormData<Product> multiPartData) {
    var file = multiPartData.File;
    var product = multiPartData.Json;
}

Or you can create your on wrapper

public class MyWrapper {
    [FromJson] // <-- This attribute is required for binding.
    public MyModel Json { get; set; }

    public IFormFile File { get; set; }
}

and then

[HttpPost]
[Consumes("multipart/form-data")] 
public async Task<IActionResult> Post([FromForm] MyWrapper myWrapper) {
    // code
}

Notes:

It automatically adds examples from class which implements IExampleProvider<MyModel>.

swashbuckle.aspnetcore.jsonmultipartformdatasupport's People

Contributors

lbabay-histech avatar machekku avatar minorityuk avatar morasiu avatar npfernandeztheillet avatar stiio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

swashbuckle.aspnetcore.jsonmultipartformdatasupport's Issues

Support Multiple IFormFile

Hello,

Excellent job done with this library.
Is there any chance that you add support for multiple files upload ?

public class MyWrapper
    {
        [FromJson]
        public Product Product { get; set; }

        public IEnumerable<IFormFile> File { get; set; } // <-- That would be awesome if we could do this
    }

    public class Product
    {
        public string Name { get; set; }

        public ProductType Type { get; set; }
    }

    public enum ProductType
    {
        Phone,
        Laptop
    }

Actual behavior when doing as above :

image

SwaggerGen Version 6> Issue

Hey! me again!
If you use SwaggerGen version 6 or greater than 6 you will receive this error:
MissingMethodException: Method not found: 'Boolean Swashbuckle.AspNetCore.SwaggerGen.SchemaRepository.TryGetIdFor(System.Type, System.String ByRef)'.

I downloaded your repo and update versions of all the packages excepts filters and used TryLookupByType instead TryGetIdFor.
Here is the change that at least works:

///


/// Generate schema for propertyInfo
///

///
private OpenApiSchema GetSchema(OperationFilterContext context, PropertyInfo propertyInfo) {
bool present = context.SchemaRepository.TryLookupByType(propertyInfo.PropertyType, out OpenApiSchema openApiSchema);
if (!present)
{
_ = context.SchemaGenerator.GenerateSchema(propertyInfo.PropertyType, context.SchemaRepository);
_ = context.SchemaRepository.TryLookupByType(propertyInfo.PropertyType, out openApiSchema);
var schema = context.SchemaRepository.Schemas[openApiSchema.Reference.Id];
AddDescription(schema, openApiSchema.Title);
AddExample(propertyInfo, schema);
}
return context.SchemaRepository.Schemas[openApiSchema.Reference.Id];
}

MultipartFormData<JsonElement> causes NullReferenceException

Using an entityWrapper typed with JsonElement
[FromForm] MultipartFormData<JsonElement> entityWrapper
generates the following error:
NullReferenceException: Object reference not set to an instance of an object.
Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations.MultiPartJsonOperationFilter.GetSchema(OperationFilterContext context, PropertyInfo propertyInfo)
Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations.MultiPartJsonOperationFilter.Apply(OpenApiOperation operation, OperationFilterContext context)
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperation(ApiDescription apiDescription, SchemaRepository schemaRepository)

Update readme

Hello, please update readme because in the last version you need to provide jsonSerializerChoice to the extension method:
i.e.
services.AddJsonMultipartFormDataSupport(JsonSerializerChoice.Newtonsoft);

Problem with validating GUID

Hello,

First of all, well done for this library.
It is simple, very useful and has saved me a lot of time.

I have one small problem that would be good if I could cover.
My model for JSON file consist GUID property. I have my own custom written validator [ValidGuid] which will detect if someone send valid GUID or not.

image

This is my controller.

image

Problem is, that validator is not working if someone send invalid Guid. { "customerId": " ", "name": "Ivan"}

This is an error.

image

If I change CustomerId type to string it is working, but I would like to use it as Guid if it is possible.

Execute button does nothing

When clicking the Execute button in Swagger, nothing happens, no console output, no packets sent. If i make the query from Postman everything work as expected.

Imcompatible parameter in SwaggerGen

Hello, me again!

If you use this option DescribeAllParametersInCamelCase() in?
services.AddSwaggerGen(o => {
o.SwaggerDoc("v1", new OpenApiInfo {
Title = "Demo",
Version = "v1"
});
o.DescribeAllParametersInCamelCase();
});
then the functionality doesn't work.
Change to lowercase properties is a workaround, but I don't know if it's the best!

Need .NET 6 support

This package is absolutely wonderful, everything I needed in one place.

Can you please get a .NET 6 version of the package (with Swagger package updates) out there? I get method not found exceptions including this from a .NET 6 assembly. Cloning locally, changing the target framework, and updating the Swagger packages was all that was necessary for my solution.

Thank you!

Json is null if model was serialized as JavaScript Blob

Hello,

Firstly, thank you for this nuget package, it really simplifies this very particular case with Swashbuckle and fixes our swagger file perfectly!

We use https://openapi-generator.tech/ to generate our TypeScript API (using the typescript-axios generator). It generates this code here:

localVarFormParams.append('Json', new Blob([JSON.stringify(json)], { type: "application/json", }));

Which as an example contributes to a request like this:

-----------------------------45968866839125028722676728444
Content-Disposition: form-data; name="Json"; filename="blob"
Content-Type: application/json

{"elections":["4514da4b-2a31-491d-9810-fd1fd391f054"],"isWeighted":true,"name":"uvcs"}
-----------------------------45968866839125028722676728444
Content-Disposition: form-data; name="File"; filename="uvcs.csv"
Content-Type: application/vnd.ms-excel

... some file content ...

-----------------------------45968866839125028722676728444--

However, when this is consumed via MultipartFormData the Json property is null.

If instead it was generated this way...

localVarFormParams.append('Json', JSON.stringify(json));

The request is sent as

-----------------------------213525737619726063793723859368
Content-Disposition: form-data; name="Json"

{"elections":["4514da4b-2a31-491d-9810-fd1fd391f054"],"isWeighted":true,"name":"uvcs"}
... more ...

And this is consumed by MultipartFormData correctly.

I could try and figure out how to wrangle the generator in such a way that it doesn't try to serialise it as a blob, but I'm opening an issue here as perhaps forgiving the inclusion of filename and Content-Type for JSON is within the interest of this package?

Thank you for your time!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.