Url.RequestContext.RouteData.Values doesn't work?

3.3k views Asked by At

I know, there are a method can be used for get current URL parameter base on route map,

Url.RequestContext.RouteData.Values["id"]

But I found when I run this method return System.NullReferenceException, so I checked in the all object got in the Url.RequestContext.RouteData.Values, it is include two instance, which is [Key:Controller, Value: Blog] and [key:action, Value:BlogCommit], then I check in my route map config file immediatelly, and think that is fine with

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

What is a default config, what is the wrong with my code?

From URL it is looks like:

http://www.example.com:1925/Blog/BlogPost/1

What is the root cause? Or is there any way to find out it?

1

There are 1 answers

0
Nelson Martins On

Hello, hope it helps:

string getParameterIdValue = (string)this.RouteData.Values["id"];

Other options:

string CurrentController = (string)this.RouteData.Values["controller"];
string CurrentAction = (string)this.RouteData.Values["action"];

Got it here: https://forums.asp.net/t/1386372.aspx?Get+Route+Parameter+Value+in+Controller