[TOC]
链接
类名的末尾要加上 Controller ,末尾要继承 ControllerBase,
请求方式,对应的属性 :
| 请求方式 | 对应属性 |
|---|---|
| GET | [HttpGet] |
| POST | [HttpPost] |
| PUT | [HttpPut] |
| Delete | [HttpDelete] |
[FromQuery]
链接后面?的参数名称
C
[FromQuery(Name = "password")] string pw[FromRoute]
目录,
C
[HttpGet("api/{UrlName}/{password}")]
// "假如password = 1 ,UrlName = 2,那么链接为api/2/1 "
[FromRoute(Name = "password")] string pw,[FromRoute] string UrlName案例
C
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[ApiController] //固定
[Route("api/[controller]/[action]")]//固定
public class TextController : ControllerBase
{
[HttpGet("{UrlName}/{id}")]//链接为api/Text/{UrlName}/{id}
public ActionResult<string> UrlML1(string UrlName, int id)
{
return Ok(UrlName + id);
}
[HttpGet("{UrlName}/{id}")]//链接为api/Text/{UrlName}/{id}
public ActionResult<string> UrlML2([FromRoute(Name = "UrlName")] string Name, [FromRoute(Name = "id")] int cId)
{
return Ok(Name + cId);
}
[HttpGet("{UrlName}/{id}")]//链接为api/Text/{UrlName}/{id}?password=?Repassword=
public ActionResult<resultss> linkParameters
(
[FromRoute(Name = "UrlName")] string Name,
[FromRoute(Name = "id")] int cId,
[FromQuery(Name = "password")] string pw,
[FromQuery] string Repassword
)
{
return Ok(new resultss { data = Name + cId + pw + Repassword });
}
}
public class resultss
{
public string data { get; set; }
}
}传输JSON
c
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("api/[Controller]/[action]")]
public class TextJsonController : ControllerBase
{
[HttpPost]
public IActionResult PostJson(StudentDto studentDto)
{
Student student = new Student();
//逻辑处理
return Ok(student);
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string age { get; set; }
public string sex { get; set; }
}
public class StudentDto
{
public string Name { get; set; }
public string age { get; set; }
public string sex { get; set; }
}
}