I am new to ASP.NET MVC. I read Professional ASP.NET MVC 3 and it has two pages talk about Ambient Route Values but I don't understand how it works. I search "asp.net mvc ambient route values" on google and still not find any articles or websites that explain what is it or how it works.
I want to know what is "Ambient Route Values" in ASP.NET MVC? How it works?
RouteData is a property of the base Controller class, so RouteData can be accessed in any controller. RouteData contains route information of a current request. You can get the controller, action or parameter information using RouteData as shown below. Example: RouteData in MVC.
A route is a URL pattern. Routing is a pattern matching process that monitors the requests and determines what to do with each request. In other words we can say Routing is a mechanism for mapping requests within our MVC application. The Routing mechanism passes the request to the handler.
The three segments of a default route contain the Controller, Action and Id.
Route values are the values extracted from a URL based on a given route template. Each route parameter in a template will have an associated route value and is stored as a string pair in a dictionary.
Ambient route values are related to all those values that are not needed for the current route outbound processing.
Take for instance this route definition:
routes.MapRoute(
"Complex",
"{securityArea}/{permission}/{action}/{id}",
new { controller = "Administration", action = "List", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
User does some administration, so he's currently on URL served by the first route definition:
/users/change/apply/45
He edits some form on this URL and posts data back.
Now if we take a look of the URL generation in #4. What happens?
They get added to the URL as well:
/Home/Index/?securityArea=Users&permission=Change
And we don't want that.
That's why they're called ambient because they are just *hanging in there orphaned in the request. This is my explanation of ambient route values. Hopefully explained in an understandable way.
I've also written about removing these ambient values in one of my blog posts where I've provided a custom route class that does this removal.
Ambient route values in the book that you linked also refer to outbound route processing but it talks about ambient values as those that we don't need to supply for outbound route processing because they will be taken from current values (namely controller and action may as well be ambient values).
Book though doesn't talk about the problem with ambient route values that I outlined in my upper answer. All defined route values can be ambient and they may cause problems when we don't realise how routing works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With