gpt4 book ai didi

c# - MVC 6 多个获取方法

转载 作者:可可西里 更新时间:2023-11-01 03:04:00 29 4
gpt4 key购买 nike

我正在尝试为每个 Controller 支持多个 Get() 方法,以及仅通过 web api 访问的特别命名的方法。我已经在 MVC 5 中完成了此操作,但似乎无法弄清楚它是如何在 MVC 6 中完成的。有什么想法吗?谢谢。

最佳答案

不能有多个具有相同 url 模式的 Get 方法。您可以使用属性路由并为不同的 url 模式设置多个 GET 方法。

[Route("api/[controller]")]
public class IssuesController : Controller
{
// GET: api/Issues
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "item 1", "item 2" };
}

// GET api/Issues/5
[HttpGet("{id}")]
public string Get(int id)
{
return "request for "+ id;
}

// GET api/Issues/special/5
[HttpGet("special/{id}")]
public string GetSpecial(int id)
{
return "special request for "+id;
}
// GET another/5
[HttpGet("~/another/{id}")]
public string AnotherOne(int id)
{
return "request for AnotherOne method with id:" + id;
}
// GET api/special2/5
[HttpGet()]
[Route("~/api/special2/{id}")]
public string GetSpecial2(int id)
{
return "request for GetSpecial2 method with id:" + id;
}
}

您可以看到我使用了 HttpGetRoute 属性来定义路由模式。

通过上面的配置,你会得到下面的响应

Request Url : yourSite/api/issues/

结果 ["value1","value2"]

Request Url : yourSite/api/issues/4

结果 请求 4

Request Url : yourSite/api/special2/6

结果 请求 GetSpecial2 方法,id:6

Request Url : yourSite/another/3

结果 请求 ID:3 的 AnotherOne 方法

关于c# - MVC 6 多个获取方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846162/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com