Kevin Bradshaw
Kevin Bradshaw

Reputation: 6427

Posting a file from ASP.NET MVC 4.6 application to ASP.NET Core Web API

I have an ASP.NET MVC web application using in the .NET Framework 4.6.

I need to be able to upload files and then forward them to a ASP.NET Core 3.1 Web API.

The problem is I can't figure out how to send files from the client app to the API.

The API accepts a request like so:

public class ReportUploadRequest
{
    public List<IFormFile> Files { get; set; }
    public int FolderId { get; set; }
    public int BrokerId { get; set; }
}

and the ASP.NET MVC application has a controller function that accepts a form submission and attempts to post to the API.

The files from the form are received in ASP.NET MVC like so:

HttpPostedFileBase[] Files

I cannot work out how to convert the HttpPostedFileBase[] Files files to the List<IFormFile> Files format required by the Web API.

I have tried to receive the files in my controller using List<IFormFile> Files but Files is null on submission

How do I prepare my form to be consumed in a format agreeable to the Web API?

Upvotes: 1

Views: 3711

Answers (2)

Fei Han
Fei Han

Reputation: 27793

I need to be able to upload files and then forward them to a ASP.NET Core 3.1 Web API.

To achieve your requirement, you can refer to the following code snippet.

In ASP.NET MVC controller action

public async Task<ActionResult> UploadFile(HttpPostedFileBase[] files)
{
    var formContent = new MultipartFormDataContent();

    foreach (var file in files)
    {
        formContent.Add(new StreamContent(file.InputStream), "files", Path.GetFileName(file.FileName));

    }

    var myHttpClient = new HttpClient();
    var response = await myHttpClient.PostAsync("https://xxxx/xxxx/UploadFile", formContent);

    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        //...
    }

In ASP.NET Core action method

public async Task<IActionResult> UploadFile([FromForm]List<IFormFile> files)
{
    //...

Test Result

enter image description here

Upvotes: 1

Se&#241;or CMasMas
Se&#241;or CMasMas

Reputation: 5108

I am not sure that this is what you are asking for but I think it might be. I have found as long as I can get something into and out of binary, then I am golden. This also provides me with good interoperability with other languages like C+++.

If not what you are asking.. tell me and I will delete my answer.

This is what I did. I specifically needed binary data to be passed to my controller and binary data returned.

For my use case, the secret was in application/octet-stream.

[Route("api/[controller]")]
[ApiController]
public class SomeDangController : ControllerBase
{
    [HttpPost]
    [Produces("application/octet-stream")]
    public async Task<Stream> GetBinaryThingy()
    {
        using (var reader = new StreamReader(HttpContext.Request.Body))
        {
            using (MemoryStream ms = new MemoryStream())
            {
                await reader.BaseStream.CopyToAsync(ms);

                var buffer = ms.ToArray();
                //buffer now holds binary data from the client
            }
       }
       byte[] bytes_return = null  //populate your binary return here.
       return new MemoryStream(bytes_return);
   }
}

And on the client.. something like this:

    public async System.Threading.Tasks.Task<byte[]> PostBinaryStuffAsync(byte[] buffer)
    {
        ByteArrayContent byteContent = new ByteArrayContent(buffer);

        var response = await client.PostAsync(dangServerURL, byteContent);

        var responseBytes = await response.Content.ReadAsByteArrayAsync();

        return responseBytes;
    }

Upvotes: 1

Related Questions