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

时间:2019-06-12 14:37:52

标签: asp.net asp.net-core asp.net-web-api-routing

我记得从ASP.NET Web API中,只要使用HTTP命令在Web API REST方法名称前添加前缀即可(例如GetList() => HTTP GETDelete() => {{1} })以正确路由来电。

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

Get(int id, string name)

ASP.NET Web API Core中不是全部可用吗?

3 个答案:

答案 0 :(得分:1)

我们既不能执行操作重载,也不能为操作名称加上Http动词作为前缀。ASP.NETCore中的路由工作方式与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 RoutingWeb Api Core 2 distinguishing GETs

答案 1 :(得分:0)

Core 2可以使用此功能,但是我知道如何做到这一点

[Route("api/[controller]")]
[ApiController]
public class AvailableRoomsController : ControllerBase
{
    private readonly ApplicationContext _context;

    public AvailableRoomsController(ApplicationContext context)
    {
        _context = context;
    }

    // GET: api/AvailableRooms
    [HttpGet]
    public async Task<ActionResult<IEnumerable<AvailableRoom>>> GetAvailableRooms()
    {
        return await _context.AvailableRooms.ToListAsync();
    }


    // POST: api/AvailableRooms
    [HttpPost]
    public async Task<ActionResult<AvailableRoom>> PostAvailableRoom(AvailableRoom availableRoom)
    {
        _context.AvailableRooms.Add(availableRoom);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetAvailableRoom", new { id = availableRoom.Id }, availableRoom);
    }

    [HttpPut] .... etc
}

现在,将根据您指定的哪种REST操作以及发送到“ api / AvailableRooms”的模型类型(如果存在适当的操作)进行选择。

如果您右键单击Controllers文件夹并单击Add-> Controller,然后选择“带操作的API控制器,使用Entity Framework”,然后选择一个Model,Visual Studio 2019和我认为2017可以自动创建这样的控制器课程。

答案 2 :(得分:0)

您只需要将Route添加到控制器的顶部即可。

使用api,控制器和操作指定路由:

$re = '/([0-9.]+)(.+?)<(.+?)>(.+?)<(\/.+?)>/m';
$str = '4.2*<span class="exception">some text</span>';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;