1

I have tried to send file through multipart form content. The code in API like shown below:

app.MapGet("/GetFile", () =>
               {
                   MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
                   multiPartContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data; boundary=----MyGreatBoundary");

                   HttpContent content1 = new ByteArrayContent(File.ReadAllBytes(@"C:/temp/TimeAkis.txt"));
                   content1.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("TimeAkis");
                   
                   content1.Headers.ContentDisposition.FileName = "TimeAkis.txt";
                   multiPartContent.Add(content1);

                   return multiPartContent;
               });

While accessing the above api method through a console application. We couldn't get the 'MultiPartContent'.

The code shown like below:

 internal async Task Read()
{

HttpClient httpClient = new HttpClient();
            
            Uri webService = new Uri(@"https://localhost:44324/GetFile");
            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, webService);
            requestMessage.Headers.ExpectContinue = false;

            Task<HttpResponseMessage> httpRequest = httpClient.GetAsync(webService);
            HttpResponseMessage responseMessage = httpRequest.GetAwaiter().GetResult();

            string strContentType = responseMessage.Content.Headers.ContentType?.MediaType;
            if(strContentType != null && IsMultipartContentType(strContentType))
            {
                try
                {
                    var multipartcontent = await responseMessage.Content.ReadAsMultipartAsync();
                    foreach(HttpContent content in multipartcontent.Contents)
                    {

                    }
                }
                catch(Exception e)
                {
                    Console.WriteLine(e);
                    
                }
        }

}

It returns the content type as 'Json': enter image description here

Please help us to get the multipart data. (OR)

Am I wrong in creating API with multipart?.

Please suggest to me.

Thanks.

Abimanyu
  • 495
  • 2
  • 13
  • 1
    TBH I would just use `Results.File` as done [here](https://stackoverflow.com/questions/70579541/asp-net-minimal-api-how-to-return-download-files-from-url/70581289#70581289) and fixed client code accordingly. – Guru Stron Aug 03 '23 at 14:12
  • 1
    I had a test with your code and it's true that it would return json result. https://i.stack.imgur.com/QQkx4.png And I'm trying to figure out a solution based on [this question](https://stackoverflow.com/questions/21173536/web-api-post-multipartformdatacontent-can-response-return-multipartform-content) but not yet test it out. – Tiny Wang Aug 04 '23 at 10:55

0 Answers0