asp.net core 参数使用

2022/2/6 14:13:08

本文主要是介绍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; }
    }


这篇关于asp.net core 参数使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程