0

I create a .Net Core API ( I use swagger with it).

I create a controller in order to upload a picture to link it to an item.

.cs :

[HttpPut("[Action]/{id}")]
public async Task<ActionResult> Link(int id, IFormFile file)
{
    var item = await _context.Item.FirstOrDefaultAsync(t => t.Id == id);
    if (item == null)
    {
        return BadRequest("item null");
    }

    using (var memoryStream = new MemoryStream())
    {
        await file.CopyToAsync(memoryStream);
        // code to link
        return Ok(file);
    }
}

My issue is if I want to test to know if it works, I have to use postman but I want to test it in my api.

A solution exist for my issue ? For the moment it look like that : upload file

1
  • What is your .net core version and swagger version? Commented Jul 23, 2019 at 5:09

2 Answers 2

2

For Swashbuckle.AspNetCore with 4.0.1 and Swashbuckle.AspNetCore.Swagger with 4.0.1, it supports IFormFile with swagger/index.html.

Detail steps:

  1. Install package Swashbuckle.AspNetCore with 4.0.1 and Swashbuckle.AspNetCore.Swagger with 4.0.1
  2. Startup.cs

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            });
    
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
    
            app.UseMvc();
        }
    }
    
  3. ApiController

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpPut("[Action]/{id}")]
        public async Task<ActionResult> Link(int id, IFormFile file)
        {
            return Ok(id);
        }
    }
    
Sign up to request clarification or add additional context in comments.

Comments

2

IFormFile only works for multipart/form-data encoded requests. To send via JSON, you need to bind to byte[], and then send the file data as either a Base64-encoded string or a uint array (i.e. the JSON equivalent of a byte[].

Also, JSON is an object notation format, so you must bind to an object. For example:

public class MyFileUploadModel
{
    public byte[] File { get; set; }
}

Then:

public async Task<IActionResult> Link(int id, MyFileUploadModel model)

Finally, you'd send a JSON object like:

{
    "file": "[base64 encoded string here]"
}

OR

{
    "file": [1, 2, 3]
}

Where [1, 2, 3] would actually be an array of the bytes in the file (i.e. numbers 0-255).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.