Get the full route to current action

2019-06-14 21:46发布

I have a simple API with basic routing. It was setup using the default Visual Studio 2015 ASP.NET Core API template.

I have this controller and action:

[Route("api/[controller]")]
public class DocumentController : Controller
{
    [HttpGet("info/{Id}")]
    public async Task<Data> Get(string Id)
    {
        //Logic
    }
}

So to reach this method, I must call GET /api/document/info/some-id-here.

Is it possible with .NET Core, inside that method, to retrieve as a string the complete route?

So I could do for example:

var myRoute = retrieveRoute();

// myRoute = "/api/document/info/some-id-here"

2条回答
甜甜的少女心
2楼-- · 2019-06-14 22:39

You can also ask MVC to create a new route URL based on the current route values:

[Route("api/[controller]")]
public class DocumentController : Controller
{
    [HttpGet("info/{Id}")]
    public async Task<Data> Get(string Id)
    {
        //Logic

        var myRoute = Url.RouteUrl(RouteData.Values);
    }
}

Url.RouteUrl is a helper method that lets you build a route URL given any route values. RouteData.Values gives you the route values for the current request.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-06-14 22:44

You can get the complete requested url using the Request option (HttpRequest) in .Net Core.

var route = Request.Path.Value;

Your final code.

[Route("api/[controller]")]
public class DocumentController : Controller
{
    [HttpGet("info/{Id}")]
    public async Task<Data> Get(string Id)
    {
        var route = Request.Path.Value;
    }
}

Result route: "/api/document/info/some-id-here" //for example

查看更多
登录 后发表回答