Wednesday, April 27, 2016

MultipartFormDataContent Add Extension Method to Accept Custom Header Values

By default MultipartFormDataContent.Add method has three overloads.
  • Add(HttpContent content)
  • Add(HttpContent content, string name)
  • Add(HttpContent content, string name, string fileName)
In this post let’s see how we can add an extension method to MultipartFormDataContent to add a new overload method which will let us send additional parameters.
  • Add(HttpContent content, string name, string fileName, object headerValues)
This is our Extension Method.
public static void Add(this MultipartFormDataContent form, HttpContent content, string name, string fileName, object headerValues)
{
    var header = new ContentDispositionHeaderValue("form-data")
    {
        Name = name,
        FileName = fileName
    };
 
    var headerParameters = new HttpRouteValueDictionary(headerValues);
    foreach (var parameter in headerParameters)
    {
        header.Parameters.Add(new NameValueHeaderValue(parameter.Key, parameter.Value.ToString()));
    }
 
    content.Headers.ContentDisposition = header;
    form.Add(content);
}
And this is how you can pass values.
using (var multipartFormDataContent = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
    multipartFormDataContent.Add(new StreamContent(new MemoryStream(data)), name, fileName, new
    {
        Parameter1="HelloWorld"
    });
}
This is how you can read the values.
MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
 
Func<ICollection<NameValueHeaderValue>, string, string> GetHeaderValueByKey = (headerValues, key) =>
{
   if (headerValues == null)
       return null;
 
   NameValueHeaderValue nameValueHeaderValue = headerValues.FirstOrDefault(x => x.Name.Equals(key, StringComparison.OrdinalIgnoreCase));
   return nameValueHeaderValue != null ? nameValueHeaderValue.Value : null;
}; 

HttpContent file = provider.Contents.FirstOrDefault();
string parameter1Value = GetHeaderValueByKey(file.Headers.ContentDisposition.Parameters, "Parameter1");

image
Result
Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment