【问题标题】:Query string and attribute routing together for controller .NET core web API一起为控制器 .NET 核心 Web API 查询字符串和属性路由
【发布时间】:2019-02-24 17:33:02
【问题描述】:

我试图实现这样的目标

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-core asp.net-core-2.0 asp.net-core-webapi


    【解决方案1】:

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

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

    这也有效。

    【讨论】:

    • "你可以在 asp.net core 中做一个或另一个" - 所以我们不能在一个方法上做两种类型的路由。
    • [HttpGet] [Route("GetValue")] [Route("GetValue/{name}/{surname}")] 添加路由属性也适用于我。
    • 我们可以在全局级别启用查询字符串路由吗,就像在 Startup.cs 中一样?
    • 在 .Net Core 5 中,查询字符串路径无法正常工作。我在查询字符串路径上获取默认值(即空字符串)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2015-12-11
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多