Get the full route to current action

前端 未结 2 759
别那么骄傲
别那么骄傲 2020-12-11 14:45

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:



        
相关标签:
2条回答
  • 2020-12-11 15:10

    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

    0 讨论(0)
  • 2020-12-11 15:20

    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.

    0 讨论(0)
提交回复
热议问题