Get ID from URL in an action from a controller with ASP .NET?

21,794

You can get this from the RouteData:

var url = Url.RequestContext.RouteData.Values["id"];
Share:
21,794
Alex
Author by

Alex

Updated on October 03, 2020

Comments

  • Alex
    Alex over 3 years

    I work asp.net MVC, I call an action (let's call it MyAction) from MyController while I'm at the following url www.mywebapp.com/MyController/AnotherAction/123

    I need to get the 123 in MyAction, so I started to do something like this :

    var url = Request.Url;
    

    In order to parse it then get the ID.

    But I'm not sure if it's the "best" way to do it. Do you know how can I get the ID from the current URL when I am in MyAction properly and safely ?