asp.net core 参数使用
作者:互联网
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
[HttpGet("add")] // 如果使用[controller]/[action],则url变成Person/Add/add
public ActionResult<int> Add(int i, int j)
{
return i + j;
}
[HttpGet("addTwo")] // 如果使用[controller]/[action],则url变成Person/Add2/addTwo
public ActionResult<int> Add2(int i, int j)
{
return 2 * (i + j);
}
[HttpGet("div/{i}/{j}")]
public ActionResult<int> Divide(int i, int j)
{
if (j == 0)
return BadRequest("not support j == 0"); // ActionResult支持隐式转换,所以这里可以返回BadRequest
return Ok(i / j);
}
[HttpGet("school/{schoolName}/class/{classNo}")] // url的占位符和参数名相同,就不需要特别指定
public Person Get(string schoolName, [FromRoute(Name = "classNo")] int classNum)
{
return new Person(1, $"{schoolName}_{classNum}_sss");
}
[HttpPost("new/{id}")] // url的占位符和参数可以同时使用
public ActionResult NewPerson(int id, [FromBody] Person p)
{
return Ok($"{p.Name} is added with id, {id}-{p.Id}");
}
}
public class Person
{
public Person(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; init; }
public string Name { get; init; }
}
标签:core,asp,return,int,ActionResult,id,Person,net,public 来源: https://www.cnblogs.com/mryux/p/15865516.html