ASP.NET Core Web API:通过方法名称进行路由? [英] ASP.NET Core Web API: Routing by method name?

查看:537
本文介绍了ASP.NET Core Web API:通过方法名称进行路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得从ASP.NET Web API中,只要使用HTTP命令(例如GetList() => HTTP GETDelete() => HTTP DELETE)为Web API REST方法名称添加前缀就足够了,以正确路由入局呼叫

I remember from ASP.NET Web API that it's sufficient to prefix Web API REST method names with HTTP commands (e.g. GetList() => HTTP GET, Delete() => HTTP DELETE) to have incoming calls appropriately routed.

我还记得在ASP.NET Web API中进行了参数匹配,因此即使Get(int id)Get(int id, string name)也可以自动且适当地进行路由,而无需任何属性.

I also remember that in ASP.NET Web API parameter matching takes place so that even Get(int id) and Get(int id, string name) get automatically and appropriately routed without requiring any attributes.

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中不是全部可用吗?

Isn't this all available in ASP.NET Web API Core?

推荐答案

我们既不能执行操作重载,也不能在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

这篇关于ASP.NET Core Web API:通过方法名称进行路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆