繁体   English   中英

控制器 .NET 核心 Web API 的查询字符串和属性路由

[英]Query string and attribute routing together for controller .NET core web API

我试图实现这样的目标

namespace CoreAPI.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        [HttpGet]
        public string GetValue(string name,string surname)
        {
            return "Hello " + name;
        }
    }
}

我想通过使用这两个 URL 来调用这个控制器方法:

  1. http://localhost:11979/api/values/Getvalues/John/lawrance
  2. http://localhost:11979/api/values/GetValues?name=john&surname=lawrance

您可以通过在控制器方法之上定义多个路由来解决此问题

[HttpGet("GetValues")]
[HttpGet("GetValues/{name}/{surname}")]
public string GetValue(string name, string surname)
{
    return "Hi" + name;
}

这将适用于http://localhost:11979/api/values/GetValues/John/lawrancehttp://localhost:11979/api/values/GetValues?name=john&surname=lawrance

添加更多:

[HttpGet]
[Route("GetValues")]
[Route("GetValues/{name}/{surname}")]
public string GetValue(string name,string surname)
{
    return "Hello " + name + " " + surname;
}

这也有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM