Click here to Skip to main content
15,888,003 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am at learning phase and i want to post file and data to api using httpclient. i have tried this. Here is my controller code

when i pass the parameters to api, the values become null.

What I have tried:

C#
string baseUrl = ServerConfig.server_path + "/api/Payment/AddMedicineOrder"; Dictionary parameters = new Dictionary();

        parameters.Add("username",user.Username);
        parameters.Add("FullName", FullName);
        parameters.Add("Phone", Phone);
        parameters.Add("CNIC", CNIC);
        parameters.Add("address", address);
        parameters.Add("Email", Email);
        parameters.Add("dateofbirth", dateofbirth.ToShortDateString());
        parameters.Add("Gender", Gender);
        parameters.Add("PaymentMethod", PaymentMethod);
        parameters.Add("Title", Title);
        parameters.Add("PhramaList", medList);



       HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://localhost:44391/");
            MultipartFormDataContent form = new MultipartFormDataContent();
            HttpContent content = new StringContent("fileToUpload");
            HttpContent DictionaryItems = new FormUrlEncodedContent(parameters);
            form.Add(content, "fileToUpload");
            form.Add(DictionaryItems, "medicineOrder");
   var stream = PostedPrescription.InputStream;
            content = new StreamContent(stream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileToUpload",
                FileName = PostedPrescription.FileName
            };
            form.Add(content);

            var response =await client.PostAsync("/api/Payment/AddMedicineOrder", form);
            var k =response.Content.ReadAsStringAsync().Result;




Here is the Web Api where is pass the parameters then it got null , not pass the values to web api .

[HttpPost]
            public async Task<API> AddMedicineOrder(string username)
            {
                var request = HttpContext.Current.Request;
                bool SubmittedFile = (request.Files.Count != 0);
                this.Request.Headers.TryGetValues("medicineOrder", out IEnumerable<string> somestring);

                var k = somestring;
  return OK("Success");
            }
            catch (Exception ex)
            {
                return InternalServerError("Technical Error.");
            }


Please help me thanks in advance
Posted
Updated 29-Jul-18 18:18pm

1 solution

Here is code I came up with, based on yours:

static async void GoPost()
        {
            string baseUrl = "http://localhost" + "/api/Payment/AddMedicineOrder";

            Dictionary<string, string> parameters = new Dictionary<string, string>();

            parameters.Add("username", "benemanuel");
            parameters.Add("FullName", "benjamin emanuel");
            parameters.Add("Phone", "0800-0800000");
            parameters.Add("CNIC", "1234");
            parameters.Add("address", "an address");
            parameters.Add("Email", "ben@benemanuel.net");
            parameters.Add("dateofbirth", "14/05/1974");
            parameters.Add("Gender", "Male");
            parameters.Add("PaymentMethod", "Credit Card");
            parameters.Add("Title", "Mr");
            parameters.Add("PhramaList", "123");

            HttpClient client = new HttpClient();
            //client.BaseAddress = new Uri("http://localhost:54169");
            MultipartFormDataContent form = new MultipartFormDataContent();
            HttpContent content = new StringContent("fileToUpload");
            HttpContent DictionaryItems = new FormUrlEncodedContent(parameters);
            form.Add(content, "fileToUpload");
            form.Add(DictionaryItems, "medicineOrder");

            var stream = new FileStream("c:\\TemporyFiles\\test.jpg", FileMode.Open);
            content = new StreamContent(stream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileToUpload",
                FileName = "AFile.txt"
            };
            form.Add(content);

            HttpResponseMessage response = null;

            try
            {
                response = (client.PostAsync("http://localhost:54169/api/Values/AddMedicineOrder?username=ben", form)).Result;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            var k = response.Content.ReadAsStringAsync().Result;
        }


and WebApi:

[Route("api/Values/AddMedicineOrder")]
        [HttpPost]
        public HttpResponseMessage AddMedicineOrder(string username)
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
                return Request.CreateResponse(HttpStatusCode.InternalServerError);
            
            var request = HttpContext.Current.Request;
            bool SubmittedFile = (request.Files.Count != 0);

            string vals = request.Form.GetValues("medicineOrder").First();

            NameValueCollection vals2 = HttpUtility.ParseQueryString(vals);

//example values:
            string value1 = vals2.GetValues("username").First();
            string value2 = vals2.GetValues("FullName").First();

            int count = vals2.Count; // 11

            return Request.CreateResponse(HttpStatusCode.OK);
            
            
            //return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }

This only gets the dictionary values you wanted, I haven't tried to extract the file from the stream or anything else, I'll leave that up to you :)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900