1

I'm trying send a JSON file with postman and it's working. But when I'm trying to send the same contents via HttpClient it's not working.

System.IO.File.WriteAllText(dirName + "\\importproduct.json", jsonitems);
var fileByteArray = File.ReadAllBytes(dirName + "\\importproduct.json");

using (var _client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
        var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

        var response = _client.PostAsJsonAsync(url, content).Result;
        var result = response.Content.ReadAsStringAsync().Result;
    }
}

PostMan: enter image description here

Paul Kertscher
  • 9,416
  • 5
  • 32
  • 57
efecetir
  • 81
  • 1
  • 6

5 Answers5

2

Instead of using PostAsJsonAsync(); method you should use PostAsync(); So your code should be looking something like that

using (var _client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
        var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

        var response = _client.PostAsync(url, content).Result;
        var result = response.Content.ReadAsStringAsync().Result;
    }
}
  • Welcome to SO, maina :) – Leron Mar 27 '20 at 06:48
  • That is working but the main issue is application on server response me "File not found" they can't see the file but i can send it from postman by "file" key. – efecetir Mar 27 '20 at 06:52
  • 1
    @efecetir I'd recommend comparing the two requests using something like Telerik's Fiddler to see what the differences are. – ProgrammingLlama Mar 27 '20 at 07:00
  • I am not sure 100% but I am expecting HttpClient.SendJsonAsync() to set http content type to "application/json" while Postman content type will be "multipart/form-data". – Aleksandar Mitev Mar 27 '20 at 07:00
1

PostAsJsonAsync method is a generic method, it expects as the second parameter the object that will be serialized and sent in the POST body.

var obj = JsonConvert.DeserializeObject<SomeModelClass>(jsonString);
var response = await _client.PostAsJsonAsync(url, obj).Result;
Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63
1

This is based on efecetir's post above. It works for me. BTW, I also upvoted his post. My issue was I needed to set the content type at the content-based level.

var fileByteArray = File.ReadAllBytes(filePath);

HttpContent bytesContent = new ByteArrayContent(fileByteArray);
using (var httpClient = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
    var RequestUri = new Uri($"http://whatever.com/");
    //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

    formData.Headers.Add("super-secret-key", "blah");
    bytesContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
    
    //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //("multipart/form-data")); // Not needed
    formData.Add(bytesContent, "file", "blah.json");
    var response = httpClient.PostAsync(RequestUri, formData).Result;
    return await HandleResponse(response);
}
MartinN
  • 51
  • 1
  • 6
0

Thanks for your comments. I fixed it and convert my codes as below. Now it's working and much more clean.

HttpContent bytesContent = new ByteArrayContent(fileByteArray);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

            formData.Add(bytesContent, "file", "importproduct.json");
            var response = client.PostAsync(url, formData).Result;
            var result = response.Content.ReadAsStringAsync().Result;

        }
efecetir
  • 81
  • 1
  • 6
  • 2
    You can express your gratitude by upvoting and accepting the best answer and not by copy-pasting the work of others! -1 from me. – Leron Mar 27 '20 at 07:10
  • i tried the link that i shared https://stackoverflow.com/a/19664927/3363877 and it worked for my case. – efecetir Mar 27 '20 at 09:17
0

Here's code I'm using to post form information and a file

using (var httpClient = new HttpClient())
{

    var surveyBytes = ConvertToByteArray(surveyResponse);


    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var byteArrayContent =   new ByteArrayContent(surveyBytes);

    byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
       var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
    var response = await httpClient.PostAsync(url , new MultipartFormDataContent
    {  
        {byteArrayContent, "\"file\"", dirName + "\\importproduct.json"}
    });

    return response;
}

This is for .net 4.5.

Bibin
  • 492
  • 5
  • 11