Search code examples
c#asp.net-mvcpostasp.net-web-apiasp.net-web-api-routing

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 <formroot> 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);

        try
        {
            //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.


Solution

  • 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();
    doc.Load(xmlFile.InputStream);
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("ab", "www.w3.org/2001/XMLSchema-instance");
    XmlNode node = doc.SelectSingleNode("//ab:formroot", nsmgr);
    

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