1

Would anyone know how to convert the below Postman POST Body form-data parameters to C# POST request, I tried a lot using HttpClient, Web request at my end but it's not working.

enter image description here

Sample code:

var bytes = (dynamic)null;
using (HttpClient httpClient = new HttpClient())
 {
    using (var multiPartContent = new MultipartFormDataContent())
    {
        var fileContent = new ByteArrayContent(documentData);
    
        //Add file to the multipart request
        multiPartContent.Headers.Add("format_source", FORMAT_SOURCE);
        multiPartContent.Headers.Add("format_target", FORMAT_TARGET);
        multiPartContent.Add(fileContent);
    
        //Post it
        bytes = httpClient.PostAsync(CONVERSION_URL, multiPartContent).Result;
    }
}

Postman code: C# RestSharp:

var client = new RestClient("http://test-service-staging.test.com/convert");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("input", "/C:/Users/DR-11/Downloads/response_1592912235925.xml");
request.AddParameter("format_source", "abc");
request.AddParameter("format_target", "xyz");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

HTTP:

POST /convert HTTP/1.1
Host: test-service-staging.test.com
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="input"; filename="/C:/Users/DR-11/Downloads/response_1592912235925.xml"
Content-Type: text/xml

(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="format_source"

abc
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="format_target"

xyz
----WebKitFormBoundary7MA4YWxkTrZu0gW

Curl:

curl --location --request POST 'http://test-service-staging.test.com/convert' \
--form 'input=@/C:/Users/DR-11/Downloads/response_1592912235925.xml' \
--form 'format_source=abc' \
--form 'format_target=xyz'

Instead of file path, need to pass the bytes in the API.

Jayoti Parkash
  • 868
  • 11
  • 26
  • 2
    In postman, if you click on the `Code` button (pictured in the top right hand corner) that will give you a coding sample. – traveler3468 Jun 29 '20 at 13:36
  • 1
    In c# code You are adding values in header while you should be adding them in body. Did you check this https://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload – Chetan Jun 29 '20 at 13:46
  • Does this answer your question? [C# HttpClient 4.5 multipart/form-data upload](https://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload) – Chetan Jun 29 '20 at 13:46
  • var client = new RestClient("http://test-service-staging.test.com/convert"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddFile("input", "/C:/Users/DR-11/Downloads/response_1592912235925.xml"); request.AddParameter("format_source", "abc"); request.AddParameter("format_target", "xyz"); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content); Thanks @AndrewE but it's not working in .net core 2.2 – Jayoti Parkash Jun 29 '20 at 14:05
  • is the url a working one? also you are displaying the content to the console but you requests appears to be return bytes rather than plain text? – traveler3468 Jun 29 '20 at 14:05
  • No, I included a dummy one. I want the same using http client not using RestClient library. – Jayoti Parkash Jun 29 '20 at 14:07

1 Answers1

1

Ok, Here is an example of your postman request using HttpClient.
It was hard to test this without a live url, however this should hopefully help you.

Not sure if you are wanting a string or byte array for the return type, I have chosen a string however if you do want a byte array, something like this should do the trick

static async System.Threading.Tasks.Task<byte[]> SendDataAsync()
return await httpResponseMessage.Content.ReadAsByteArrayAsync();

    static async System.Threading.Tasks.Task Main(string[] args)
    {
        // Is This Returning A String Or Bytes
        string responseAsString = await SendDataAsync();
        Console.ReadKey();
    }

    static async System.Threading.Tasks.Task<string> SendDataAsync()
    {
        using (HttpClient httpClient = new HttpClient())
        using (MultipartFormDataContent formDataContent = new MultipartFormDataContent())
        {
            // Create Form Values
            KeyValuePair<string, string>[] keyValuePairs = new[]
            {
                new KeyValuePair<string, string>("format_source", "abc"),
                new KeyValuePair<string, string>("format_target", "xyz")
            };

            // Loop Each KeyValuePair Item And Add It To The MultipartFormDataContent.
            foreach (var keyValuePair in keyValuePairs)
            {
                formDataContent.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
            }

            // Get The ByteArrayContent,Reading Bytes From The Give File Path.
            // Adding It To The MultipartFormDataContent Once File Is Read.
            string filePath = @"C:\Users\andrew.eberle\Desktop\data.xml";
            ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filePath));

            // Add Content Type For MediaTypeHeaderValue.
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Add The File Under ''input'
            formDataContent.Add(fileContent, "input", System.IO.Path.GetFileName(filePath));

            // Post Request And Wait For The Response.
            HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("http://test-service-staging.test.com/convert", formDataContent);

            // Check If Successful Or Not.
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                // Return Byte Array To The Caller.
                return await httpResponseMessage.Content.ReadAsStringAsync();
            }
            else
            {
                // Throw Some Sort of Exception?
                return default;
            }
        }
    }
traveler3468
  • 1,557
  • 2
  • 15
  • 28
  • What about first parameter i.e input has value File, I have file bytes and passing in the code that you provided above and getting 500 error. – Jayoti Parkash Jun 29 '20 at 15:37
  • Updated, I have added input to the formDataContent, see how you go, Without a way to test we're flying blind. Hopefully this gets you one step closer. – traveler3468 Jun 29 '20 at 15:43
  • Now I am getting 400, It means the previous one is fine but there is something that needs to be fixed. Let me edit the code part, going to add the source code using C# RestSharp, Curl, Http. It will give a clear picture of what is missing in this code. – Jayoti Parkash Jun 29 '20 at 15:52
  • Updated, tested with webapi and received the parameters and file `formDataContent.Add(fileContent, "input", $"{System.IO.Path.GetFileName(filePath)}");` forgot to add the filename to the previous comment, if the server doesnt like the `MediaTypeHeaderValue` you should be able to comment it out to test. – traveler3468 Jun 29 '20 at 16:33
  • keep trying the updated code, but getting 400 status. – Jayoti Parkash Jun 29 '20 at 16:45
  • - httpResponseMessage {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers: { Date: Mon, 29 Jun 2020 16:48:39 GMT Server: nginx/1.16.1 Via: HTTP/1.1 forward.http.proxy:3128 Connection: keep-alive Content-Type: text/plain; charset=utf-8 Content-Length: 106 }} System.Net.Http.HttpResponseMessage – Jayoti Parkash Jun 29 '20 at 16:49
  • What about when you read the httpresponse string when you get the error? Looks like there could be a reason for the error. – traveler3468 Jun 29 '20 at 16:51
  • This is the message that I am getting in HttpResponseMessage httpResponseMessage. no other specific error details. – Jayoti Parkash Jun 29 '20 at 16:54
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/216909/discussion-between-andrewe-and-jayoti-parkash). – traveler3468 Jun 29 '20 at 23:48