Click here to Skip to main content
14,835,688 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!I have an API method that has to send both json and form-data format to the server,but I don't understand how can I achieve this.Currently I have this method which returns a 415 unsupported media type:
C#
public async Task<JObject> AddUser(User user, MediaFile file)
      {
          string userRegisterUrl = "http://10.0.2.2:53547/api/PostUser";
          HttpContent fileStreamContent = new StreamContent(file.GetStream());
          var json = JsonConvert.SerializeObject(user);
          HttpClientHandler clientHandler = new HttpClientHandler();
          clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
          try
          {
              using (var formData = new MultipartFormDataContent())
              {
                  formData.Add(fileStreamContent, Guid.NewGuid().ToString() + "jpg");
                  formData.Add(new StringContent(json.ToString()));
                  using(HttpClient client = new HttpClient(clientHandler))
                  {
                      var responce = await client.PostAsync(userRegisterUrl, formData);
                      string contents = await responce.Content.ReadAsStringAsync();
                      return (JObject.Parse(contents));
                  }
              }
          }catch(Exception ex)

          {
              throw ex;
          }
      }



How can I achieve this so that the data passed would not be affected?

What I have tried:

C#
public async Task AddUser(User user,MediaFile file)
          {
            string userRegisterUrl = "http://10.0.2.2:53547/api/PostUser";
              HttpClientHandler clientHandler = new HttpClientHandler();
              clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
  var json = JsonConvert.SerializeObject(user);
              StringContent content = new StringContent(json);
    HttpContent fileStreamContent = new StreamContent(file.GetStream());
    using (var httpClient = new HttpClient(clientHandler))
              {

                  using (var formData = new MultipartFormDataContent())
                  {

                      httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
                      formData.Add(fileStreamContent);
                      formData.Add(content);
                      var responses = await httpClient.PostAsync(userRegisterUrl, formData);
                      if (responses.IsSuccessStatusCode)
                      {
                          //var result = response.Content.ReadAsStringAsync().Result;

                      }
                  }
              }


          }
Posted
Updated 13-Aug-20 6:24am
Comments
Richard MacCutchan 13-Aug-20 12:03pm
   
You need to look at the API code to see what format the data needs to be in.
Eliza Maria 13-Aug-20 12:25pm
   
Thank you for your response.I don't actually understand what you're saying by that as i have the image which is form-data and the user details which are json format.I can't transfer the image to the server as json as it is received by the server as IFormFile and uploaded in a folder.

1 solution

WebAPI built-in formatters only support the following media types: application/json, text/json, application/xml, text/xml and application/x-www-form-urlencoded

A quick look at what error means:
Quote:
The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

Reference: 415 Unsupported Media Type - HTTP | MDN[^]

Now, in your context, you are trying to do:
API method that has to send both json and form-data format to the server

This means:
1. You need to make sure the server accepts multiple format as content type payload.
2. Once you are sure of that, then for multipart/form-data, which is what you are sending, look at ASP.NET WebApi: MultipartDataMediaFormatter[^]

Try out.
   
Comments
Eliza Maria 13-Aug-20 12:35pm
   
Thank you,that's what i wanted to know :D
Sandeep Mewara 13-Aug-20 12:36pm
   
:thumbsup:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900