Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post data using MultipartFormDataContent from HttpClient

Tags:

c#

I have a WebAPI service which reads post data including file data using

HttpContext.Request as key value pairs
HttpContext.Current.Request["LoadId"]

Now I am trying to write and Console application using HttpClient but not able to make it work

private static bool AddException(string vin, string loadId, string sessionId)
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri("url")
            };
            ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;

            const string quickCode = "01-01-1"; 
            const string inspectionType = "Loading";
            const string inspectorCode = "001";
            const string numberOfImages = "1";
            const string imageNumber = "1";
            const string exceptionType = "Driver";
            const string imageType = "exception";
            var date = DateTime.Now.ToString();

            var content = new MultipartFormDataContent();
            var values = new[]
                    {
                        new KeyValuePair<string, string>("LoadId", loadId),
                        new KeyValuePair<string, string>("VIN", vin),
                        new KeyValuePair<string, string>("SessionId", sessionId),
                        new KeyValuePair<string, string>("QuickCode", quickCode),
                        new KeyValuePair<string, string>("strInspectionType", inspectionType),
                        new KeyValuePair<string, string>("InspectorCode", inspectorCode),
                        new KeyValuePair<string, string>("NoOfImages", numberOfImages),
                        new KeyValuePair<string, string>("Imageno", imageNumber),
                        new KeyValuePair<string, string>("strExceptionType", exceptionType),
                        new KeyValuePair<string, string>("ImageType", imageType),
                        new KeyValuePair<string, string>("DateTimeOffset", date)
                    };
            var fileContent = new ByteArrayContent(File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Desert.jpg"
            };
            content.Add(fileContent, "file", "11");

            foreach (var keyValuePair in values)
            {
                content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
            }

            var response = client.PostAsync("Exception/AddException", content).Result;
            var exceptionResult = response.Content.ReadAsAsync<bool>().Result;

            return exceptionResult;
        }

The above is the code. But not able to read code from the service

I have no control over service code and cant change it

like image 928
ravi shanker Avatar asked May 18 '13 14:05

ravi shanker


1 Answers

Did you try this code at Post form data along with files to Web Api2. You can merge both the code blocks. It works perfectly fine for me.

Web Api Code to read files

using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

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

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

}

Web Api Code to read form data

public async Task<HttpResponseMessage> PostFormData()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

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

    try
    {
        await Request.Content.ReadAsMultipartAsync(provider);

        // Show all the key-value pairs.
        foreach (var key in provider.FormData.AllKeys)
        {
            foreach (var val in provider.FormData.GetValues(key))
            {
                Trace.WriteLine(string.Format("{0}: {1}", key, val));
            }
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
like image 178
Himanshu Patel Avatar answered Nov 15 '22 00:11

Himanshu Patel