Web API (一)

一、JS请求方式

页面内容
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>各种非主流操作</title> <script src="../javascript/jquery-1.8.2.js"></script>
<script>
内容
</script> </head> <body> <input type="text" value="" id="userid" /> <input type="text" value="" id="name"/> <input type="text" value="" id="userid2" /> <input type="text" value="" id="name3" /> <hr/> <input type="button" value="get提交" onclick="wds_getuset()" /> <input type="button" value="get提交两个参数" onclick="wds_getuset2()" /> <hr/> <input type="button" value="post提交" onclick="wds_postuset()" /> <input type="button" value="post提交两个参数" onclick="wds_postuset2()" /> <input type="button" value="post提交多个参数" onclick="wds_postuset3()" /> <hr/> <input type="button" value="put提交" onclick="wds_putuset()" /> <input type="button" value="put提交一个参数" onclick="wds_putuset2()" /> <hr/> <input type="button" value="delete提交" onclick="wds_deleteuset()" /> <input type="button" value="delete提交一个参数" onclick="wds_deleteuset2()" /> <hr/> <div id="pj"> </div> </body> </html>
有关Get操作数据

        //get 一个参数
        function wds_getuset() {
            var userid = $("#userid").val();
            var url = "/api/user/GetUser/" + userid;
            $.getJSON(url, function (msg) {
                alert(msg);msg是个json串
                var model = JSON.parse(msg);
                alert(model["Name"]);
                var model1 = $.parseJSON(msg);
                alert(model1.Name);
                var html = '<p>' + msg + '</p>';           
                $("#pj").append(html);
            });
        }

        //get 二个参数
        function wds_getuset2() {
            var accunt = $("#userid").val();
            var pwd = $("#name").val();
            $.ajax({
                url: "/api/user/GetTwoUser",
                type: "get",
                data:{"name":accunt,"pwd":pwd}, 【传2个数据可以成功,查过2个就会失败,多参数时,可以使用后面用到的方法】
                success: function (data) {
                    alert(data);
                }
            });

        }

后台:

  [HttpGet]
        public string GetUser(int id)
        {
            try
            {
                IXiao_UserBLL bll = new Xiao_UserBLL();
                var model = bll.GetUserById(ConnectPool.connect, id);

                return JsonConvert.SerializeObject(model);
            }
            catch
            {
                return null;
            }
        }

     [HttpGet]
       public void GetTwoUser(string name, string pwd)
        {
            
        }
Post方法
jquery部分  

当产地一个参数是 参数如果写成键值对的形式,数据是传不过去的


      //post 一个参数
        function wds_postuset() {
            var accunt = $("#userid").val();
            $.post("/api/user/UserPost", { "": accunt }, function (msg) {
                if (msg == "error") {
                    alert("添加失败!");
                } else {
                    alert("恭喜你,添加成功!");
                }
            });
            $.ajax({
                url: "/api/user/UserPost",
                type: "post",
                data: {  "":accunt },
                success: function(data) {
                    alert(data);
                }
            });

        }
        //post  二个参数
        function wds_postuset2() {
            var accunt = $("#userid").val();
            var pwd = $("#name").val();
            $.post("/api/user/adduser", { "Account": accunt, "PassWord": pwd }, function (msg) {
                if (msg == "error") {
                    alert("添加失败!");
                } else {
                    alert("恭喜你,添加成功!");
                }
            });

            $.ajax({
                url: "/api/user/adduser",
                type: "post",
                data: { "Account": accunt, "PassWord": pwd },
                success: function(data) {
                    alert(data);
                }
            });

            var job= {
                "Account": accunt,
                "PassWord": pwd
            }
            $.ajax({
                url: "/api/user/adduser",
                type: "post",
                data: JSON.stringify(job),
                contentType:"application/json",
                success: function (data) {
                    alert(data);
                }
            });
        }

        //post 多个实体
        function wds_postuset3() {
            var accunt = $("#userid").val();
            var pwd = $("#name").val();
            var accunt2 = $("#userid2").val();
            var pwd2 = $("#name3").val();
            var us= {
                "Account": accunt,
                "PassWord": pwd
            }

            var sc= {
                "SchoolName": accunt2,
                "SchoolAddress": pwd2
            }
            $.ajax({
                url: "/api/user/PostTwoUser",
                type: "post",
                data: JSON.stringify({ "xiao_user": us, "xiao_school": sc }),
                contentType: "application/json",
                success: function (data) {
                    alert(data);
                }
            });
        }

后台

  [HttpPost]
        public string UserPost([FromBody]string accunt)
        {
            try
            {
                IXiao_UserBLL bll = new Xiao_UserBLL();
                var model = bll.GetUserById(ConnectPool.connect, Convert.ToInt32(accunt));
                return JsonConvert.SerializeObject(model);
            }
            catch (Exception)
            {
                return null;
            }
        }

        [HttpPost]
        public string adduser([FromBody] xiao_userModel model)
        {
            try
            {
                IXiao_UserBLL bll = new Xiao_UserBLL();
                model.AddTime = DateTime.Now;
                var result = bll.AddUser(ConnectPool.connect, model);
                return result > 0 ? "ok" : "error";
            }
            catch (Exception)
            {
                return "error";
            }
        }

        [HttpPost]
        public void PostTwoUser([FromBody]JObject obj)
        {
            try
            {
                //dynamic 类型与 object 类型的行为是一样的。 但是,不会用编译器对包含 dynamic 类型表达式的操作进行解析或类型检查。 编译器将有关该操作信息打包在一起,并且该信息以后用于计算运行时操作。 在此过程中,类型 dynamic 的变量会编译到类型 object 的变量中。 因此,类型 dynamic 只在编译时存在,在运行时则不存在
                dynamic json = obj;
                JObject user = json.xiao_user;
                JObject school = json.xiao_school;
            }
            catch (Exception)
            {

                throw;
            }
        }
Put 方法部分 Jquery

        //put 无参
        function wds_putuset() {
  
            $.ajax({
                url: "/api/user/PutUserName",
                type: "put",
                success: function (data) {
                    alert(data);
                }
            });
        }

        //put 一个参数
        function wds_putuset2() {
            var id = $("#userid").val();
            
          $.ajax({
              url: "/api/user/PutUserOne",
              type: "put",
              data: { "": id },
              success: function (data) {
                  alert(data);
              }
          });

            var us = {
                "Account": id,
            }
            $.ajax({
                url: "/api/user/PutUserOne",
                type: "put",
                data: JSON.stringify({ xiao_user: us }),
                contentType: "application/json",
                success: function (data) {
                    alert(data);
                }
            });
        }


后台

        [HttpPut]
        public string PutUserName()
        {
            try
            {
                IXiao_UserBLL bll = new Xiao_UserBLL();
                var model = bll.GetUserById(ConnectPool.connect, 6565);
                return JsonConvert.SerializeObject(model);

            }
            catch (Exception)
            {
                return null;
            }
        }

        [HttpPut]
       // public string PutUserOne([FromBody]JObject obj)  多个参数时使用
        public string PutUserOne([FromBody]string  userid)
        {

            return null;
        }
delete 部分 jquery

      //delete 无参数
        function wds_deleteuset() {
            $.ajax({
                url: "/api/user/Deleteuser",
                type: "delete",
                success: function (data) {
                    alert(data);
                }
            });
        }

后台
      [HttpDelete]
        public void Deleteuser()
        {
            
        }

这个和其他的都相同

 webapi传参数详解 http://www.cnblogs.com/landeanfen/p/5337072.html

 

二、后台请求方式

HttpWebRequest POST请求webapi:如果参数是简单类型,比如字符串(注意,拼接的字符串要HttpUtility.UrlEncode才行,否则服务端会丢失特殊字符&后面的数据)

要点:如下代码统一设置为:ContentType = "application/x-www-form-urlencoded";

服务端代码1:URL格式为 POSTapi/Values

public string Post([FromBody] string value)

则客户端Post的数据:拼接的字符串必须以 =开头,否则服务端无法取得value。例如:=rfwreewr2332322232 或者 {'':value}


服务端代码2:URL格式为 POST api/Values?value={value}

public string Post(string value)

则客户端Post的数据:需要url里拼接出KeyValue这样的数据

服务端代码3:URL格式为 POST api/Values

public string Post()

则客户端Post的数据:无要求。例如:key=rfwreewr2332322232。

服务端:可以用HttpContext.Current.Request.InputStream或者HttpContext.Current.Request.Form[0]都可以获取



如果post的参数类型比较复杂,则需要自定义类

要点:如下代码统一设置为:ContentType = "application/json";

服务端代码1:URL格式为 POST api/Values

public string Post([FromBody] Model value)或者 public string Post(Model value)

则客户端Post的数据:{\"id\":\"test1\",\"name\":\"value\"}。服务端会自动映射到对象。
        public static string Post(string url, dynamic model)
        {
            WebRequest request = WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "POST";
            var data = JsonConvert.SerializeObject(model);
            //将字符串数据转化为字节串,这也是POST请求与GET请求区别的地方
            byte[] buffer = Encoding.UTF8.GetBytes(data);

            //用于将数据写入Internet资源
            Stream stream = request.GetRequestStream();
            stream.Write(buffer, 0, buffer.Length);

            WebResponse response = request.GetResponse();

            //从网络资源中返回数据流
            stream = response.GetResponseStream();

            StreamReader sr = new StreamReader(stream, Encoding.UTF8);

            //将数据流转换文字符串
            string result = sr.ReadToEnd();

            //关闭流数据
            stream.Close();
            sr.Close();

            return result;

        }
    [HttpPost]
        public string userInfo(dynamic data)
        {
            var mm = JsonConvert.DeserializeObject<dynamic>(data.ToString());
            return JsonConvert.SerializeObject(new { UserId = 12, Age = 13 });
        }

  

 

 

posted @ 2015-07-17 16:55  逍遥帝君  阅读(197)  评论(0编辑  收藏  举报