如何使用httpclient C#将文件和数据发布到api [英] How to post file and data to api using httpclient C#

查看:83
本文介绍了如何使用httpclient C#将文件和数据发布到api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



当我将参数传递给api时,值变为null。



< b>我尝试了什么:




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

What I have tried:

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;









这里是Web Api,传递参数然后它变为null,而不是将值传递给web api。







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

推荐答案

以下是我提出的代码,基于你的代码:



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;
        }





和WebApi:





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 :)


这篇关于如何使用httpclient C#将文件和数据发布到api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆