C# Multipart/Form-Data Submit Programmatically

C# Multipart form-data in HttpClient Post REST API

All, Finally i am able to reproduce the Postman code in C# programmatically.

I able to add the "metadata" property in the multipart form-data.

Reference: Upload Files Using HttpClient

string Seshat_URL = "https://azr-stg.dev03.abs.ase.southcentralus.us.wc.net/files/v11";
using (var multiPartStream = new MultipartFormDataContent())
{

multiPartStream.Add(new StringContent("{}"), "metadata");
multiPartStream.Add(new ByteArrayContent(filecontent, 0, filecontent.Length), "file", docName);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Seshat_URL);
request.Content = multiPartStream;
//"application/json" - content type
request.Headers.Accept.Add(JSON_GENERIC_MEDIA_TYPE);
request.Headers.Add("X-Client-Id", ClientId);
request.Headers.Add("Tenant-Id", TenantId);

HttpCompletionOption option = HttpCompletionOption.ResponseContentRead;
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

using (HttpResponseMessage response = _httpClient.SendAsync(request, option).Result)
{
if (response.IsSuccessStatusCode)
{
var deserializedObject = JsonConvert.DeserializeObject<Wc.MCM.UIMVC.Helpers1.BlobResponse>(response.Content.ReadAsStringAsync().Result);
return deserializedObject.fileId.ToString();
}
}

}//End Try

Multipart forms from C# client

This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment.

public class PostData
{

private List<PostDataParam> m_Params;

public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}

public PostData()
{
m_Params = new List<PostDataParam>();

// Add sample param
m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));
}


/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
// Get boundary, default is --AaB03x
string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();

StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine(boundary);

if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: text/plain");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}

sb.AppendLine(boundary);

return sb.ToString();
}
}

public enum PostDataParamType
{
Field,
File
}

public class PostDataParam
{


public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}

public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}

To send the data you then need to:

HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";
PostData pData = new PostData();

byte[] buffer = encoding.GetBytes(pData.GetPostData());

// Set content length of our data
oRequest.ContentLength = buffer.Length;

// Dump our buffered postdata to the stream, booyah
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();

// get the response
oResponse = (HttpWebResponse)oRequest.GetResponse();

Hope thats clear, i've cut and pasted from a few sources to get that tidier.

Call A Multi-Part Form Method Programmatically

Try to use HttpClient and send MultipartFormDataContent in controller

using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent("testA"), "A");//string
content.Add(new StringContent("testB"), "B");
content.Add(new StringContent("testBB"), "B");//string[]
content.Add(new StringContent("testC"), "C");
content.Add(new StringContent("testCC"), "C");

//replace with your own file path, below use an image in wwwroot for example
string filePath = Path.Combine(_hostingEnvironment.WebRootPath + "\\Images", "myImage.PNG");

byte[] file = System.IO.File.ReadAllBytes(filePath);

var byteArrayContent = new ByteArrayContent(file);

content.Add(byteArrayContent, "file", "myfile.PNG");

var url = "https://locahhost:5001/foo/bar";
var result = await client.PostAsync(url, content);
}
}

Reading file input from a multipart/form-data POST

You may take a look at the following blog post which illustrates a technique that could be used to parse multipart/form-data on the server using the Multipart Parser:

public void Upload(Stream stream)
{
MultipartParser parser = new MultipartParser(stream);
if (parser.Success)
{
// Save the file
SaveFile(parser.Filename, parser.ContentType, parser.FileContents);
}
}

Another possibility is to enable aspnet compatibility and use HttpContext.Current.Request but that's not a very WCFish way.

How to send multipart/form-data to ASP.NET Core Web API?

Maybe you should try decorate controller input and model with [FromForm] attribute?
See more info here: web api parameters binding.

In given example your controller action should look like this:

[HttpPost("/api/account"), Authorize]
public void SaveUser([FromForm]UserModel info)

In model:

[FromForm(Name="avatar")]
public IFormFile Avatar { get; set; }

[FromForm(Name="name")]
public string Name { get; set; }


Related Topics



Leave a reply



Submit