.Net Core tips - upload files using Swagger

foreword

   With the popularity of the front-end and back-end separation development model, back-end personnel are more likely to write server-side API interfaces. It is a common function to call the interface to realize file upload. At the same time, it also needs an interface for selecting file upload. You can write the front-end interface to upload, and you can use Postman and curl to simulate the upload request. The above method is somewhat cumbersome. Swagger is used as an API documentation and debugging tool. If it can provide a file upload interface (not provided by default), it will be more convenient for file upload prompts. This article will introduce how to use Swagger to upload files.

 

step

1. Install Swagger

Install-Package Swashbuckle.AspNetCore

 

2. Configure Swagger middleware

In Startup.ConfigureServices add:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});

 

In Startup.Configure add:

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

 

3. Write the API

// POST api/values
[HttpPost]
public void Post(IFormFile file)
{
    //TODO:Save file...
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, IFormFile file)
{
    //TODO:Save file...
}

 

4. Write SwaggerFileUploadFilter

public class SwaggerFileUploadFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
            !context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        var fileParameters = context.ApiDescription.ActionDescriptor.Parameters.Where(n => n.ParameterType == typeof(IFormFile)).ToList();

        if (fileParameters.Count < 0)
        {
            return;
        }

        operation.Consumes.Add("multipart/form-data");

        foreach (var fileParameter in fileParameters)
        {
            var parameter = operation.Parameters.Single(n => n.Name == fileParameter.Name);
            operation.Parameters.Remove(parameter);
            operation.Parameters.Add(new NonBodyParameter
            {
                Name = parameter.Name,
                In = "formData",
                Description = parameter.Description,
                Required = parameter.Required,
                Type = "file"
            });
        }
    }
}

 

5. Register SwaggerFileUploadFilter

c.OperationFilter<SwaggerFileUploadFilter>();

 

6. View the results

POST method:

 

PUT method:

 

Principle analysis

  The key to using Swagger to upload files is SwaggerFileUploadFilter, which inherits from Swashbuckle's IOperationFilter, that is, it only works on Swagger and will not affect other modules.

  Let's take a look at the logic of the Apply method in SwaggerFileUploadFilter:

  1. Determine whether the request method is POST or PUT. If it is other request methods, it is basically impossible for a file upload operation.

  2. Find the parameter of type IFormFile in the method.

  3. Set Consumers to "multipart/form-data".

  4. In the description of the IFormFile type parameter, replace In with formData and Type with File.

 

Source address

https://github.com/ErikXu/.NetCoreTips/tree/master/SwaggerFileUpload

 

References

http://www.talkingdotnet.com/how-to-upload-file-via-swagger-in-asp-net-core-web-api/

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324638839&siteId=291194637