0

I'm trying to make a POST API call to update a product on Prisync with multipart/formdata text field. The call responses success on POSTMAN: enter image description here

enter image description here

but it returns 400 Bad request error in .NET code:

enter image description here

Can you please let me know what's wrong here?


Here is my code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;

namespace PrisyncPost
{
    class Program
    {
        static string apikey = "luan.t44@gmail.com";
        static string apitoken = "3a3206b37763722c0fc6431b713d9239";
        static void Main(string[] args)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://prisync.com/api/v2/edit/product/id/10117217");
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers["apikey"] = apikey;
            httpWebRequest.Headers["apitoken"] = apitoken;
            httpWebRequest.ContentType = "multipart/form-data; boundary=&";

            MultipartFormDataContent form = new MultipartFormDataContent();
            form.Add(new StringContent("test test test"), "name");

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                foreach (var item in form)
                    streamWriter.Write(item);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
        }
    }
}
Luan Tran
  • 376
  • 1
  • 3
  • 15
  • 1
    Please try [method A](https://stackoverflow.com/a/4015346/3181933). It seems that you're trying to mix HttpWebRequest with content from HttpClient. `streamWriter.Write(item)` will write (as a string literal) `System.Net.Http.StringContent` because it's not meant to be used this way. Alternatively, replace your entire `streamWriter` section with `form.SerializeToStream(httpWebRequest.GetRequestStream();` Note that in your Postman request, you have what would be `FormContent` in C#, not `MutlipartFormDataContent`. – ProgrammingLlama May 26 '21 at 03:24
  • The keys in the headers (should be "id") has to be same as postman : httpWebRequest.Headers["apikey"] = apikey; httpWebRequest.Headers["apitoken"] = apitoken; – jdweng May 26 '21 at 05:52

0 Answers0