gpt4 book ai didi

ASP.NET 核心 Web API : Routing by method name?

转载 作者:行者123 更新时间:2023-12-03 15:58:41 24 4
gpt4 key购买 nike

我记得在 ASP.NET Web API 中,用 HTTP 命令(例如 GetList() => HTTP GETDelete() => HTTP DELETE )作为 Web API REST 方法名称的前缀就足以正确路由传入调用。

我还记得在 ASP.NET Web API 中会发生参数匹配,甚至 Get(int id)Get(int id, string name)无需任何属性即可自动适本地路由。

public class MyController
{
public ActionResult Get(int id) => ...

public ActionResult Get(int id, string name) => ...

public ActionResult DeleteItem(int id) => ...
}

这不是在 ASP.NET Web API Core 中都可用的吗?

最佳答案

我们既不能执行 Action 重载,也不能将 Action 名称作为 Http 动词前缀。ASP.NET Core 中路由的工作方式与 ASP.NET Web Api 中的工作方式不同。

但是,您可以简单地组合这些操作,然后在内部分支,因为如果您作为查询字符串发送,则所有参数都是可选的

[HttpGet]
public ActionResult<string> Get(int id, string name)
{
if(name == null){..}
else{...}
}

或者,如果您发送路由数据,则需要使用属性路由来指定每个 api:
[HttpGet("{id}")]       
public ActionResult<string> Get(int id)
{
return "value";
}


[HttpGet("{id}/{name}")]
public ActionResult<string> Get(int id, string name)
{
return name;
}

引用 Attribute Routing , Web Api Core 2 distinguishing GETs

关于ASP.NET 核心 Web API : Routing by method name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56564757/

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