且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core Web API:通过方法名称进行路由?

更新时间:2023-02-15 20:48:51

我们既不能执行操作重载,也不能在Http谓词前添加操作名称.ASP.NETCore中路由的工作方式不同于ASP.NET中的路由方式网络Api.

Neither could we do action overloads nor prefix action name as Http verb.The way routing works in ASP.NET Core is different than how it did in ASP.NET Web Api.

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

However, you can simply combine these actions and then branch inside, since all params are optional if you send as querystring

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

或者,如果您发送路由数据,则需要使用属性路由来指定每个api:

Or you need to use attribute routing to specify each api if you send in route data:

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


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

请参阅属性路由 Web api核心2区分GETs