首页 > 解决方案 > 一起为控制器 .NET 核心 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

标签: c#asp.net-coreasp.net-core-2.0asp.net-core-webapi

解决方案


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

[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;
}

这也有效。


推荐阅读