ASP.NET CORE,ASP.NET MVC 使用FormData请求接口—HttpClient使用FormData请求接口,.NET HTTP请求接口multipart/form-data

ASP.NET CORE 使用FormData请求接口

##在获取请求接口通常都是使用的json传递参数,首次遇到在客户提供接口需要FormData作为请求参数,找网上一顿找也没有找到一个合适的,到最后还是在官网中看到MultipartFormDataContent类,总算是找到对应的解决方案啦

            string url = "http://127.0.0.1/test"; //接口请求地址
            string boundary = DateTime.Now.Ticks.ToString("X");
            var formData = new MultipartFormDataContent(boundary);
            formData.Add(new StringContent(Request.Form["num1"]),"parametername");//参数一
            formData.Add(new StringContent(Request.Form["num2"]), "parametername");//参数二
            HttpClient httpClient = new HttpClient();
            var response = httpClient.PostAsync(url, formData).Result;
            var responseContent = response.Content.ReadAsStringAsync().Result;//获取接口返回的值
            return Json(responseContent);

json格式请求接口

using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://127.0.0.1/");//接口请求域名
                string num1 = "111";
                string num2= "222";                
                var requestJson = JsonConvert.SerializeObject(new {num1 = num1 , num2= num2 })
                HttpContent httpContent = new StringContent(requestJson);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var result = client.PostAsync("apis/activeInsurance", httpContent).Result.Content.ReadAsStringAsync().Result;// apis/activeInsurance 请求域名后的接口地址
                return Json(result);
            }

你可能感兴趣的:(.Net,MVC,FormData请求接口,http,post,接口,c#)