从另一个控制器创建到控制器的URL链接

时间:2018-04-26 18:34:04

标签: c# asp.net-core

我在ASP.NET Core 2.0中开发了一个WebApi RESTful。 从控制器A中的操作方法我想为位于不同控制器B中的操作方法创建URL地址:

[Route("api/applications/{idbcon}/bcontrollers")]
public class BController : Controller{
    [HttpGet({idbcon}), Name = "ActionB"]
    public IActionResult ActionB(int idbcon, [FromHeader(Name = "Accept")] string mediatype){
        return OK();
    }
}
[Route("api/applications/{idapp}/bcontrollers/{idbcon}/acontrollers")]
public class AController: Controller{
    [HttpGet(), Name = "GetURLBController"]
    public IActionResult GetURLBController()
    {
        var url = /* Here I would like to get the link to "ActionB" that belong to a Controller "BController" */;
        return Ok(url);
    }
}

任何建议???

1 个答案:

答案 0 :(得分:3)

使用actioncontroller参数的IUrlHelper.Action重载:

public class AController : Controller
{
    [HttpGet]
    public IActionResult GetURLBController()
    {
        var url = Url.Action("ActionB", "BController");
        return Ok(url);
    }
}

IUrlHelper是您从Controller基类继承的内容,公开为Url属性。