簡體   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