回来目录

   public class User_Info
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Info { get; set; }
    }

下边定义3个扑朔迷离类型对象

实业的特性,在行使HttpClient时,直接为FormUrlEncodedContent对象赋三个键值对的集聚即可,上面分别介绍一下

    [CorsAttribute("http://localhost:3321")]
    public class RegisterController : ApiController
    {
        public static List<User_Info> Model = new List<User_Info>()
        {
            new User_Info{Id=1,Name="zzl",Info="zzl是楼主"},
            new User_Info{Id=2,Name="zhz",Info="zhz是zzl的儿子"},
            new User_Info{Id=3,Name="zql",Info="zql是zzl的妻子"},
            new User_Info{Id=4,Name="bobo",Info="bobo是zzl的朋友"}
        };

        // GET api/values
        public IEnumerable<User_Info> Get()
        {
            return Model;
        }
        // GET api/values/5
        public User_Info Get(int id)
        {
            var entity = Model.FirstOrDefault(i => i.Id == id);
            return entity;
        }
        // GET api/values/5?leval=1
        public HttpResponseMessage Get(int id, int leval)
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("<em style='color:red'>成功响应(id,level)</em>", System.Text.Encoding.UTF8, "text/html")
            };
        }
        // POST api/values
        public HttpResponseMessage Post([FromBody]User_Info value)
        {
            Model.Add(new User_Info
            {
                Id = value.Id,
                Info = value.Info,
                Name = value.Name,
            });
            //用户登陆相关
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("添加数据成功,用户ID:" + value.Id, System.Text.Encoding.UTF8, "text/plain")
            };
        }
        // PUT api/values?userid=5
        public HttpResponseMessage Put(int userid, [FromBody]User_Info value)
        {
            var entity = Model.FirstOrDefault(i => i.Id == userid);
            entity.Info = value.Info;
            entity.Name = value.Name;
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("修改数据成功,主键:" + userid + ",对象:" + value.Name)
            };
        }

        // DELETE api/values/5
        public HttpResponseMessage Delete(int id)
        {
            Model.Remove(Model.FirstOrDefault(i => i.Id == id));
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("删除数据成功")
            };
        }
     $.ajax({
            url: "http://localhost:52824/api/register",
            type: "POST",
            data: { Id: 5, Name: '新来的', Info: '大家好' },//这里键名称必须为空,多个参数请传对象,api端参数名必须为value
            success: function (data) {
                console.log("post:" + data);
            }
        });

        $.ajax({
            url: "http://localhost:52824/api/register",
            type: "GET",
            success: function (data) {
                for (var i in data) {
                    console.log(data[i].Id + " " + data[i].Name);
                }
            }
        });
       /// <summary>
        /// HttpClient实现Post请求
        /// </summary>
        static async void dooPost()
        {
            string url = "http://localhost:52824/api/register";
             //设置HttpClientHandler的AutomaticDecompression
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            //创建HttpClient(注意传入HttpClientHandler)
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(new Dictionary<string, string>()       
                {    {"Id","6"},
                     {"Name","添加zzl"},
                     {"Info", "添加动作"}//键名必须为空
                 });

                //await异步等待回应

                var response = await http.PostAsync(url, content);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }

        }
        /// <summary>
        /// HttpClient实现Get请求
        /// </summary>
        static async void dooGet()
        {
            string url = "http://localhost:52824/api/register?id=1";
            //创建HttpClient(注意传入HttpClientHandler)
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                //await异步等待回应
                var response = await http.GetAsync(url);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();

                //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
        }
        /// <summary>
        /// HttpClient实现Put请求
        /// </summary>
        static async void dooPut()
        {
            var userId = 1;
            string url = "http://localhost:52824/api/register?userid=" + userId;

            //设置HttpClientHandler的AutomaticDecompression
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            //创建HttpClient(注意传入HttpClientHandler)
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(new Dictionary<string, string>()       
                {
                   {"Name","修改zzl"},
                   {"Info", "Put修改动作"}//键名必须为空
                });

                //await异步等待回应

                var response = await http.PutAsync(url, content);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }

        }

 归来目录

Console程序中选择HttpClient对象开展落到实处

而最关键的地点依然在各种客户端调用的时候,首先,你无法指望客户端去引用你的程序集,因为,无法平台不恐怕落到实处那种引用(java
& c#,js & C#,php &
c#),所以,在调用时索要有它们分别的不二法门,而JS的ajax调用时,直接动用json对象即可,键名对象

图片 1

上边修改上次的api部分,让它对那个目的开始展览操作

HTML的JS实现

上一讲中牵线了动用HttpClient怎样去调用三个行业内部的Web
Api接口
,并且大家领悟了Post,Put方法只可以有1个FromBody参数,再有多个参数时,上讲关系,必要将它封装成三个目的开始展览传递,而那讲首要围绕这一个话题来说,接口层添加一个新类User_Info,用来拓展数量传递,而客户端选用网页ajax和控制台HttpClient的艺术分别展开落到实处,Follow
me!

结果截图

相关文章

网站地图xml地图