Paul Coan Paul Coan - 1 year ago 130
C# Question

multipart form - Web API

I have a ASP.NET MVC project that needs an API controller which will accept a posted multipart form and extract the data out of the

xml tag (which is highlighted)

I am struggling on getting this working any help would be greatly appreciated

enter image description here

Currently I have a controller called UploadController and this is the code I currently have

public class UploadController : ApiController
public async Task<HttpResponseMessage> PostFormData()
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.BadRequest);

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

//Need to get the data from within the formroot tag

return Request.CreateResponse(HttpStatusCode.OK);
catch (Exception e)
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);

I am unsure the best way to get the data from within the formroot, also forgive me if any of the code above is not correct.

Answer Source

Inside the web API controller you can access the XML file by using the code below :-

HttpPostedFile xmlFile = HttpContext.Current.Request.Files[0];

If you have more than one files posted, replace Files[0] with respective count 1 or 2 etc. Now you can load the file into a XmlDocument Object and extract the required node from it like :-

XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ab", "");
XmlNode node = doc.SelectSingleNode("//ab:formroot", nsmgr);

Then you can perform whatever you functionality is provided with the node.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download