ASP.NET Webapi中各种请求格式

API项目不关心前端页面,只提供数据
返回字符串

[HttpGet]
        public string GetCourse()
        {
            //请求数据库
            return "GetCourse返回的结果webApi2";
        }
        //前端调用
        <a href="/api/Course">GetCourse</a>

2.传参返回字符串

  [HttpGet]
    public string GetCourseById(int courseId)
    {
        return $"GetCourseById(int courseId)方法返回的结果:{courseId}";
    }
    //前端调用
    <a href="/api/Course/?courseId=1000">GetCourseById</a>

使用WebAPI的特性路由避免在实际开发中,http请求的方法可能是相同的,比如post请求,而且请求参数也相同的情况

    //两个相同的参数,在请求过程中,服务器只能识别到第一个
         [HttpGet]
        public string GetCourseById(int courseId)
        {
            return $"GetCourseById(int courseId)方法返回的结果:{courseId}";
        }
        [Route("Course/QueryCourseById")]
        [HttpGet]
        public string QueryCourseById(int courseId)
        {
            return $"QueryCourseById(int courseId)方法返回的结果:{courseId}";
        }
        //前端页面请求
        
           <input type="button" id="btn1" value="测试特性路由-Get" />
           
           //js
           <script src="~/Content/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btn1").click(function () {
            $.get("/Course/QueryCourseById", { courseId: 1000 }, function (data, status) {
                alert(data);
            });
        });
    });

</script>

注意:post的请求中,如果有参数,则在参数传递过程中,不能使用键值对方式传递,在使用特性路由时,post请求参数不能直接传参,get与post在请求时,通过主体实现,httpGet通过明文方式传递,httpPOST通过消息传递,默认为明文方式,在参数类型前添加关键字[FromBody]

   [HttpPost]
        [Route("Course/UpdateCourse")]
        public string UpdateCourse()
        {
            return "您正在修改课程";
        }
        [HttpPost]
        [Route("Course/DeleteCourse")]
        public string DeleteCourse([FromBody]int  courseId)
        {
            return "post请求到的Id"+courseId;
        }
        //前端调用
         <input type="button" id="btn2" value="测试特性路由更新-post" />
    <input type="button" id="btn3" value="测试特性路由删除-post" />
    
    //js
       $(function () {
                  $("#btn2").click(function () {
                $.post("/Course/UpdateCourse", null, function (data, status) {
                    alert(data);
                });
                  });
                $("#btn3").click(function () {
                    $.post("/Course/DeleteCourse",{ "": 2000 }, function (data, status) {
                        alert(data);
                    });
                });
           });

总结:get方式非常简单,重点是Post请求
无参的post请求
和Get请求方式相同,只不过在客户端 . g e t 和 .get和 .get.post的区别,同时只需添加[httpPost]标记特性即可
一个参数的post请求
和Get方式不一样,动作方法参数上面必须添加[FromBody]标记,否则访问不到,同时WebApi请求传递的参数,也有特定的格式,而这种格式并不是键值对方式。WebAPI模型绑定器寻找的时候,并不是按照Key去查找。而是空字符串
多个参数的post请求
将多个参数封装成实体对象,在对象前标记[FromBody]

  [HttpPost]
        [Route("Course/AddCourse")]
        public string AddCourse(Models.Course course)
        {
            return $"Post请求到的课程Id={course.Id},Name={course.Name},Category={course.Category} price={course.Price}";
        }
        //js
              $("#btn4").click(function () {
                $.post("/Course/AddCourse", { Id: 2000, Name: "WebApi2", Category: "必修", Price: 36 }, function (data, status) {
                    alert(data);
                });
            });

路由前缀[RoutePrefix(“api/Teacher”)] 定义路由前缀后,就可以省略一些在方法前的特性路由前缀

   /// <summary>
    /// 路由前缀
    /// </summary>
    [RoutePrefix("api/Teacher")]
      public class TheacherController : ApiController
    {

        [HttpGet]
        [Route("")]
        public int GetAllTeacherCount()
        {
            return 10;
        }
        [HttpPost]
        [Route("QueryTeacherById")]
        public string QueryTeacherById([FromBody] int teacherId)
        {
            return "上课了" + teacherId;
        }
    }
    
    //js调用
     $("#btn5").click(function () {
       $.get("/api/Teacher", null, function (data, status) {
             alert(data);
          });
         });
       $("#btn6").click(function () {
         $.post("/api/Teacher/QueryTeacherById", { "":10001 }, function (data, status) {
            alert(data);
        });
   });

路由约束。对参数类型进行强制约束

 //路由约束
        [Route("GetCount/{age:int=0}")]
        [HttpGet]
    
        public string GetCount(int age)
        {
            return $"查询讲师年龄等于{age}共计10人";
        }
        //js
          $("#btn7").click(function () {
                $.get("/api/Teacher/GetCount", { age:35 }, function (data, status) {
                    alert(data);
                });
            });


Get请求汇总
Get无参请求

   [Route("GetStudent")]
        [HttpGet]
        public string GetStudent()
        {
            return "10";
        }
        //js
         $("#btn1").click(function () {
            $.get("/api/Student/GetStudent", null, function (data, status) {
                alert(data);
            });
        });

Get 2个参数的请求,get请求不需要在参数前添加[FromBody]关键字,而post请求需要

   [Route("GetStudent")]
        [HttpGet]
        public string GetStudent()
        {
            return "10";
        }
        //js
         $("#btn1").click(function () {
            $.get("/api/Student/GetStudent", null, function (data, status) {
                alert(data);
            });
        });

Get 请求实体参数

   [Route("QueryStudent")]
        [HttpGet]
        //FromUri指定操作参数来自传入HttpRequestMessage的URI
        public string QueryStudent([FromUri]Student student)
        {
            //地址栏的传递参数存在于queryString中,可以获取
            //string StudentName = System.Web.HttpContext.Current.Request.QueryString["StudentName"];
            //string name2 = System.Web.HttpContext.Current.Request.QueryString["StudentName"];
            return $"学员基本信息{student.StudentId},{student.StudentName}";
        }
        //js
           $("#btn3").click(function () {
            $.get("/api/Student/QueryStudent", { StudentId: 1212, StudentName: "admin", Age: 20, PhoneNumber: "111111" }, function (data, status) {
                alert(data);
            });
        });

Get 接收json字符串,并转化为实体对象

     [HttpGet]
        [Route("GetStudentByJson")]
        public string GetStudentByJson(string jsonStudent)
        {
            //将Json字符串反序列化
            Student model = Newtonsoft.Json.JsonConvert.DeserializeObject<Student>(jsonStudent);
            return $"{model.PhoneNumber} { model.StudentId}  { model.StudentName}";
        }
        
        //js
               $("#btn4").click(function () {
            //包装数据
            //stringify() 将一个JavaScript值(对象或数组)转换为一个Json字符串
            var jsonStudent = { StudentId: 1212, StudentName: "admin", Age: 20, PhoneNumber: "111111" }
            $.get("/api/Student/GetStudentByJson", { jsonStudent: JSON.stringify(jsonStudent) }, function (data, status) {
                alert(data);
            });
        });

没有添加Get特性 如何请求数据? 需要在方法名称前加关键字

   /// <summary>
        /// Get请求,没有添加[HTTPGET]特性,并且方法没有Get关键字出现,请求时不能提交的
        /// </summary>
        /// <param name="studentId"></param>
        /// <returns></returns>
        public string   QueryStudentScore(string studentId)
        {
            return $"学员:{studentId}成绩是90";
        }

        /// <summary>
        /// 方法开头有Get关键字出现,请求可以提交
        /// </summary>
        /// <param name="studentId"></param>
        /// <returns></returns>
        [Route("GetQueryStudentScore")]
        public string GetQueryStudentScore(string studentId)
        {
            return $"学员:{studentId}成绩是90";
        }
        //js
        $("#btn5").click(function () {
      
            $.get("/api/Student/QueryStudentScore", { studentId:1001 }, function (data, status) {
                alert(data);
            });

        });
        $("#btn6").click(function () {
 
            $.get("/api/Student/GetQueryStudentScore", {studentId:1001 }, function (data, status) {
                alert(data);
            });

        });

集合对象的获取

[Route("GetStudentList")]
[HttpGet]

        public  List<Student> GetStudentList(string className)
        {
            return new List<Student> {
                new Student { StudentId=1001,StudentName="admin",Age=23,PhoneNumber="122"} ,
                 new Student { StudentId=1002,StudentName="admin1",Age=23,PhoneNumber="1223"},
                  new Student { StudentId=1003,StudentName="admin2",Age=23,PhoneNumber="1232"},
                  new Student { StudentId=1004,StudentName="admin3",Age=23,PhoneNumber="1223"},
            };

        }
        //js
              $("#btn7").click(function () {
            $.get("/api/Student/GetStudentList", {className:"一班" }, function (data, status) {
                //遍历对象集合
                jQuery.each(data, function (i, item) {
                    alert(item.StudentName + " " + item.Age)
                });
            });

        });

post方法总结

一个参数请求post(注意需要使用FormBody)

[HttpPost]
        [Route("GetScoreById")]
        public string GetScoreById([FromBody] int scoreId)
        {
            return $"Post请求返回信息{scoreId}";
        }
        //js
        $("#btn1").click(function () {
            $.post("/api/Score/GetScoreById", { "": 1 }, function (data, status) {
                alert(data);
            });
        });

含有两个参数的post,在方法前写入两个类型是请求错误的,并列使用FromBody是不允许的。须写成dynamic
public string GetScoreById([FromBody] int scoreId,[FromBody] string name)

基于dynamic实现多个参数的请求
      /// <summary>
        /// Post基于dynamic实现多个参数的请求()
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetScoreByDynamic")]
        public string GetScoreByDynamic(dynamic param)
        {
            return $"Post多个参数的请求返回的成绩信息{param.studentId} {param.studentName}";
        }
        //js
          $("#btn2").click(function () {
            $.ajax({
                type: "post",
                url: "/api/Score/GetScoreByDynamic",
                contentType: 'application/json',
                data: JSON.stringify({
                    studentId: 1000,
                    studentName: "Tony",
                    age: 20
                }),
                success: function (data, status) {
                    alert(data)
                }
            });
        });

基于Json传递实体对象,注意在post中的参数StudentId、studentName必须是实体类Student中的属性

 [HttpPost]
        [Route("QueryName")]
        public string QueryName(Student student)
        {
            return $"返回学员信息{student.StudentName}";
        }
//js
       $("#btn3").click(function () {
            $.post("/api/Score/QueryName", { StudentId: 1001, studentName: "Tony" }, function(data, status) {
                alert(data);
            });
        });

基础数据类参数+实体参数一起传递

 /// <summary>
        /// 基础数据类型参数—+实体参数类型一起传递
        /// 通用dynamic类型,接收复杂的Json字符
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
         [HttpPost]
        [Route("MultiParam")]
        public string MultiParam(dynamic param)
        {
            //方法[1]通过key动态获取对应的数据,并根据需要转换
            var teacher = param.Teacher.ToString();
            var student = Newtonsoft.Json.JsonConvert.DeserializeObject<Student>(param.Student.ToString());

            //方法[2]对应动态类型中包含的子对象页可以通过jObject类型转换
            Newtonsoft.Json.Linq.JObject JStudent = param.Student;
            var studentModel = JStudent.ToObject<Student>();//将JsonObject转化成具体的实体对象
            return $"Teacher={teacher} Student>studentId={student.StudentId}";
        }
        //js
        $("#btn4").click(function () {

            var data = {
                "Teacher": "Tony",
                "Student": {
                    "StudentId": 10001,
                    "StudentName":"Bill"
                }
            }
            $.ajax({
                type: "post",
                url: "/api/Score/MultiParam",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (data, status) {
                    alert(data)
                }
            })
        });

数组类型参数请求

[HttpPost]
        [Route("ArrayParam")]
        public  string  ArrayParam(string[] param)
        {
            return $"{param[0]}---{param[1]}----{param[2]}";
        }
        //js
         $("#btn5").click(function () {

            var data = ["90", "33","66"]
            $.ajax({
                type: "post",
                url: "/api/Score/ArrayParam",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (data, status) {
                    alert(data)
                }
            })
        });

集合对象参数请求

 [HttpPost]
        [Route("ListParam")]
        public string ListParam(List<Student> student)
        {
            return $"对象集合{student.Count.ToString()}";
        }
        //js
          $("#btn6").click(function () {
                var data = [
                    { StudentId: 1001, StudentName: "tom", Age: 20, PhoneNumber: "136000154" },
                    { StudentId: 1002, StudentName: "tom", Age: 20, PhoneNumber: "136000154" },
                    { StudentId: 1003, StudentName: "tom", Age: 20, PhoneNumber: "136000154" },
                ]
            $.ajax({
                type: "post",
                url: "/api/Score/ListParam",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (data, status) {
                    alert(data)
                }
            })
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值