html调用webapi绘图,使用HttpClient调用WebAPI接口,含WebAPI端示例

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;usingSystem.Net.Http;usingSystem.Text;usingSystem.Net.Http.Headers;usingSystem.IO;usingNewtonsoft.Json;namespaceWebApi.Controllers

{public classClientController : Controller

{//GET: Client

publicActionResult Index()

{//HttpClient client = new HttpClient();//string Url = "http://localhost:33495/api/default/";

#region 原始方式调用

//StringContent方式调用//var result = client.PostAsync(Url, new StringContent("111", Encoding.UTF8, "application/json")).Result;//ByteArrayContent方式//var data = Encoding.UTF8.GetBytes("\"ddd\"");//data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new menu { menuId = 1, menuName = "33333" }));//data = Encoding.UTF8.GetBytes("{menuId:1,menuName:333}");//var content = new ByteArrayContent(data);//content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");//var result_byte = client.PostAsync(Url, content).Result;//PostAsJsonAsync方式//client.PostAsJsonAsync(Url, "ss");

#endregion

#region 多参数传参

//client.PutAsJsonAsync(string.Format("{0}{1}?guid={2}", Url, 5, Guid.NewGuid()), "test");

#endregion

#region 服务端上传图片

//服务端上传图片//using (HttpClient client = new HttpClient())//{//var content = new MultipartFormDataContent();// //添加字符串参数,参数名为qq//content.Add(new StringContent("123456"), "qq");//string path = Server.MapPath("/Images/test.jpg");// //添加文件参数,参数名为files,文件名为123.png//content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "test.jpg");//var requestUri = "http://localhost:33495/api/default/";//var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;//Response.Write(result);//}

#endregion

return null;

}publicActionResult HTML()

{returnView();

}publicActionResult Upload()

{returnView();

}

}

}