关于 [HttpGet("index")]和 [HttpGet("/index")]访问区别

108 阅读2分钟

一引子

这是我学习他人项目遇到的一个问题,于是在网上寻找答案。终于明白了,现在把它分享出来。希望能帮助像我一样菜的人。

二 问题和解释

[HttpGet("index")]和[HttpGet("/index")]的区别在于路由路径的定义方式。

[HttpGet("index")]使用相对路径来定义路由,它会将“index”作为当前控制器的路由前缀的一部分。例如,如果该控制器的路由前缀是“/api/employees”,那么使用[HttpGet("index")]后,该方法的完整路由路径就是“/api/employees/index”。

而[HttpGet("/index")]则使用绝对路径来定义路由,即以斜杠开头的路径。它会将“/index”视为根路由的一部分,不考虑当前控制器的路由前缀。因此,无论当前控制器的路由前缀是什么,使用[HttpGet("/index")]后,该方法的完整路由路径都是“/index”。

所以,如果在应用程序中有一个名为“index”的控制器或视图,使用[HttpGet("/index")]可能会导致路由冲突或访问错误的控制器或视图。而[HttpGet("index")]则可以避免这个问题,因为它只是将“index”作为当前控制器的一个子路由,而不是完整的路由路径。

因此,如果要使用绝对路径来定义路由,请确保在整个应用程序中没有其他控制器或视图使用相同的路由路径。否则,建议使用相对路径来定义路由,以避免路由冲突和访问错误的控制器或视图.

三 示例代码说明

 [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {

        [HttpGet("A")]
        public JsonResult A()
        {
            return new JsonResult(new { Code = 200, Message = "Success!" });
        }

        [HttpGet("/B")]
        public JsonResult B()
        {
            return new JsonResult(new { Code = 200, Message = "Success!" });
        }

        [HttpGet("/C")]
        public JsonResult C()
        {
            return new JsonResult(new { Code = 200, Message = "Success!" });
        }
        [HttpGet("/AB")]
        public JsonResult AB()
        {
            return new JsonResult(new { Code = 200, Message = "Success!" });
        }
        [HttpGet("/BC")]
        public JsonResult BC()
        {
            return new JsonResult(new { Code = 200, Message = "Success!" });
        }
        [HttpGet("/AC")]
        public JsonResult AC()
        {
            return new JsonResult(new { Code = 200, Message = "Success!" });
        }

        [HttpGet("/ABC")]
        public JsonResult ABC()
        {
            return new JsonResult(new { claims = User.Claims });
        }


        /// <summary>
        /// 任何人都不能访问
        /// </summary>
        /// <returns></returns>
        [HttpGet("D")]
        public JsonResult D()
        {
            return new JsonResult(new { Code = 200, Message = "Success!" });
        }

        [HttpGet("error")]
        public JsonResult Denied()
        {
            return new JsonResult(
                new
                {
                    Code = 0,
                    Message = "访问失败!",
                    Data = "此账号无权访问!"
                });
        }
    }

对于 [HttpGet("A")]之类的访问,根据上面的解释,是应该用下面的方式访问

https://localhost:44304/api/Test/A

对于 [HttpGet("/B")], [HttpGet("/AB")], [HttpGet("/AC")] 之类的 用下面的方式访问

https://localhost:44304/B
https://localhost:44304/AB
https://localhost:44304/AC

四 结论

一个是相对路径,一个是绝对路径。如果他们的使用方式不对就会出现找不到的错误。

参考链接:www.cnblogs.com/whuanle/p/1…