Resolving 'Malformed FormData Request' errors in C#

Created by Kesh Bhamidipaty, Modified on Thu, 13 Jun at 11:50 PM by Kesh Bhamidipaty

This article outlines likely causes for 'Malformed FormData Request' errors when using the Stability API in C#, and gives example approaches for resolving them.



Symptoms


The following shows the relevant bit of the HTTP response seen when making a request to a Stability API endpoint in C#:


{"success":false,"message":"Malformed FormData request. Content-Disposition header in FormData part is missing a name."}


Possible Root Cause & Solution


C# may not quote the Content-Disposition header by default. In this case, the following helper functions can be used as a workaround:


private static StringContent stringFormField(string name, string value) {
  var formField = new StringContent(value);
  formField.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
  {
    Name = $"\"{name}\""
  };
  return formField;
}

private static async Task<ByteArrayContent> imageFormField(string name, string imagePath, string mimeType) {
  var filename = Path.GetFileName(imagePath);
  var imageBytes = await File.ReadAllBytesAsync(imagePath);
  var formField = new ByteArrayContent(imageBytes);
  formField.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
  formField.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
  {
    Name = $"\"{name}\"",
    FileName = $"\"{filename}\""
  };
  return formField;
}


Which can be used like so:


using var formData = new MultipartFormDataContent
{
    stringFormField("prompt", "large nebula full for stars both near and far"),
    stringFormField("right", "500"),
    await imageFormField("image", imagePath, "image/png")
};




Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article