REST风格

REST 介绍

实现举例

访问一个Controller

[Route("[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
        [HttpGet]
        public string Get()
        {
          return "你好";
        }
}

访问有参数Controller

[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 "用户名或密码错误";
        }
    }
}
[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;
        }

}

posted on 2022-01-10 20:31  软嘴唇  阅读(33)  评论(0编辑  收藏  举报

导航