REST风格
REST 介绍
实现举例
访问一个Controller
[Route("[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
public string Get()
{
return "你好";
}
}
访问有参数Controller
- 通过 http://localhost:5000/Login/Get?userNo=2765483955&pwd=123456 访问;
- 用“?”隔开,“&”多参数
[Route("[controller]/[action]")]
[ApiController]
public class LoginController : ControllerBase
{
//用户登录
[HttpGet]
public string Get(string userNo,string pwd)
{
return "号码:"+userNo+",密码:"+pwd;
}
}
常用HTTP 动词
- Get 获取数据
- Post 数据插入
- Put 数据更新
- Delete 数据删除
访问对应Web API控制器 (只是写个大概访问方式)
[Route("[controller]/[action]")]
public class LoginController : ControllerBase{
[HttpGet]
public string Get(string userNo,string pwd)
{
User user = userDal.GetUserByUserNoAndPassword(userNo, pwd);
if (user != null)
{
return user.UserName+"登录成功";
}
else
{
return "用户名或密码错误";
}
}
}
- 添加 http://localhost:5000/Login/Post?userNo=147258369&userName=小蓝&userLevel=19&userPassWord=123456789
[Route("[controller]/[action]")]
public class LoginController : ControllerBase{
[HttpPost]
public string Post(string userNo, string userName, string userLevel, string userPassWord)
{
User user = new User(userNo, userName, Convert.ToInt32(userLevel), userPassWord);
if (userDal.InsertUser(user) > 0)
{
return "添加成功";
}
else
{
return "添加失败";
}
}
}
[HttpPut]
public string Put(int uId, string userNo, string userName, int userLevel, string userPassWord)
{
User user = userDal.GetUserById(uId);
if (user != null )
{
int i = userDal.UpdateUserById(uId, new User(userNo, userName, userLevel, userPassWord));
if (i > 0)
{
return "修改成功";
}
}
return "修改失败";
}
[HttpDelete]
public string Delete(int uId)
{
if(userDal.DeleteUserById(uId) > 0) return "删除成功";
return "删除失败";
}
指定访问Controller Api
[Route("[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
[HttpGet("{test1}/{test2}")]
public string Test(string test1,string test2)
{
return test1+","+test2;
}
}