且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用httpclient C#将文件和数据发布到api

更新时间:2022-10-31 13:42:49

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



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