构建WebApi服务的步骤为:
1,创建空的WebApi项目
2,添加空的WebApi控制器(控制器存放位置在Controllers文件夹中)
3,在控制器中添加方法(用于处理客户端发送的请求)
备注:下面只演示代码,创建过程缺失
创建控制器,编写处理请求的方法
public class GetResponseController:ApiController{//标识该方法属于GET请求[HttpGet]//标识该方法的请求路径[Route("api/showname")]public string ShowName(string userName){return string.Format("您输入的姓名是:{0}",userName);}[HttpPost][Route("api/getstudentinfo")]public Student GetStudentInfo([FromBody]Student student){List<Student> StudentList = Data.DataHelper.IntiStudentList(); //加载数据集if(StudentList!=null&&StudentList.Any()){Student currentStudent =StudentList.Where(c=>c.StudentId.Equals(student.StudentId)&&c=>c.StudentName.Equals(student.StudentName)).FirstOrDefault();if(currentStudent!=null){return currentStudent;}}return null;}}
备注:如果使用[FromBody]去传递string类型的参数,服务端接收到的值一直都是null,因此最好是dto模型来进行传递即可。
数据源
public class DataHelper{public static List<Student> IntiStudentList(){return new List<Student>(){new Student(){StudentId="001",StudentName="Rotu"},new Student(){StudentId="002",StudentName="Jack"},};}}[Serializable]public class Student{public string StudentId{get;set;}public string StudentName{get;set;}}
页面发送请求
<!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 type="text/javascript" src="/Script/jquery-1.10.2.min.js"></script><script type="text/javascript">$(function(){//使用ajax发送get请求$("#GetRequest").click(function(){var userName =$("#UserName").val();if(userName==""){alert("请输入姓名");return;}$.ajax({url:"/ap/showname?username="+userName,type:"GET",success:function(data){alert(data);}});});//使用ajax发送post请求$("#PostRequest").click(function(){var studentId =$("#StudentId").val();var studentName =$("#StudentName").val();if(studentId==""||studentName===""){alert("编号或姓名为空");return;}var student ={StudentId:studentId,StudentName:studentName};$.ajax({url:"/api/getstudentinfo",type:"POST",dataType:"JSON",data:student,success:function(data){alert(data);}});});})</script></head><body>姓名:<input type="text" id="UserName"/><button id="GetRequest">发送GET请求</button>编号:<input type="text" id="StudentId" name="StudentId"/>姓名:<input type="text" id="StudentName" name="StudentName"/><button id="PostRequest">发送POST请求</button></body></html>
