Search code examples
c#asp.netjsonmultipartform-datamultipart

How to receive MultipartFormData on ASP.NET C#


I'm working with an iOS guy. He wants to upload images through WebAPI ASP.NET. I've to make a call that can receive those images.
He said he is using AFNetworking to send data through AFMultipartFormData. My question is that how can I receive this at my end? Should I take the data in JSON format? Or what measures needs to be done for this purpose? I want to know the whole process as this is my first time working with MultipartFormData.

UPDATE
Based on the answer I used this:

[HttpPut]
        public IHttpActionResult GetPatientFilesAction(int id, Model.Patients.PatientFiles patientFile)
        {
            Model.Patients.PatientFiles pFile=new Model.Patients.PatientFiles();
            try
            {
                HttpPostedFile xmlFile = HttpContext.Current.Request.Files[0];

                var fileForm = HttpContext.Current.Request.Form;
                var fileKey = HttpContext.Current.Request.Form.Keys[0];
                string[] jsonformat = fileForm.GetValues(fileKey);
                 pFile = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.Patients.PatientFiles>(jsonformat[0]);
            }
            catch (Exception ex)
            {

                pFile.ErrorMessage = ex.ToString();
            }
            return Ok(pFile);
        }

But the iOS guy got:

Request failed: unsupported media type (415)


Solution

  • Inside the web API controller you can access the image file 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.

    And then you can access the JSON using the code :

    var fileForm = HttpContext.Current.Request.Form;
    var fileKey = HttpContext.Current.Request.Form.Keys[0];
    string[] jsonformat = fileForm.GetValues(fileKey);
    var yourModel = JsonConvert.DeserializeObject<YourClassType>(jsonformat[0]);
    

    If you have more than one json strings posted, replace jsonformat[0] with respective count 1 or 2 etc.