How routing is done in asp.net mvc
Each route contains the following info,
1. the url
2. the curly braces that specify the match
3. the constraints for the inputs in the url parameters
Each route should be anything that inherits from the RouteBase.
****************
foreach route in the routescollection do,
{
1. The url in the route should match the incoming url
2. The contents for the curly braces must match in the incoming url
3. The constraints should also match with the route taken from the
routes collection.
4. If a match occurs, then the route is considered as a valid one
}
for every route match to be done, the routebase supplies the URL, the
curlybrace dictionary with its replacement from the request URL, route
parameter values with the optional ones for which no value was
received from the i/p request.
3. The route handler is passed with the requestContext [url, cookies,
authentication data, request data etc]
once a first route match is done, the routing mechanism stops finding
the next match thereafter
The values for the action method parameters are taken from the
RouteData's values. Ex: RouteData.Values["name"] will be used for an
action method like public ActionResult GetUserData(string
name){..........}
To mark a parameter as optional in a route, set the route as follows,
routes.MapRoute("","Catalog/{color}", new {controller="catalog",
action="list", color=(string)null});
Here the (string)null is to specify that a null is used for a string
datatype parameter.
HttpVerbConstraints
*******************
RouteConstraints to restrict HTTPGet an HTTPPost methods,
this can be done via the attributes on the action methods or can be
done in the routing level itself. If done in the routing level, the
constraint is applied at an earlier stage in the pipeline than the
attributes in the action methods.
Constraints
**********
When a constraint failed, then the route next to the that evaluates to
false is evaluated.
sample:
var ieOnlyRoute = new Route("Customer/Edit", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE"),
cookieConstraint = new CookieConstraint()
})
};
Also it is possible to map controllers from a different namespace, sample
To accept any number of segments in the url, use the catchall
parameter in the route config in global.asax as follows,
var ieOnlyRoute = new Route("Customer/Edit/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
}),
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
To enable the file access also to be routed instead of rendering it
dierectly use the following route setting in the global.asax after 1
or more routes are registered there.
routes.RouteExistingFiles = true;
To render the content files only of specific folder the following
settings can be used in the global.asax.cs
routes.RouteExistingFiles = true;
routes.IgnoreRoute("Content/{file}.{abc}");
routes.IgnoreRoute("Content/{*restOfTheUrl}");
The above 2 lines are equivalent to routes.Add(new
Route("Content/{file}.{abc}", new StopRoutingHandler());
********************************************************************************************
Handling the Outgoing URL's
*************************
The way in which the Html.ActionLink renders the url parameters is
based on the routing defitions
Sample1 [w/o explicit routing]
*************************
var ieOnlyRoute = new Route("Customer/Edit/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
//,cookieConstraint = new CookieConstraint()
}),
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
For this routing configuration, the links generated are looking like
<a href="/Customer/Edit?id=firstname">Edit</a>
However, if the above routing configuration is modified to incorporate
the id parameter in the url parameter, the rendered markup will vary
as follows,
var ieOnlyRoute = new Route("Customer/Edit/{id}/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit",
id = UrlParameter.Optional
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
//,cookieConstraint = new CookieConstraint()
}),<%: Html.ActionLink("Click me", "MyAction",
"MyController", "https",
"www.example.com", "anchorName", new { param = "value" },
new { myattribute = "something" }) %>
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
Now, the markup rendered will look like,
<a href="/Customer/Edit/firstname">Edit</a>
This makes the difference and gets the clean url.
To generate the fully qualified URL's, refer the overloads of the
ActionLink method that takes the domain, uri scheme etc to generate a
fully absolute URL.
<%: Html.ActionLink("Click me", "MyAction", "MyController", "https",
"www.example.com", "anchorName", new { param = "value" },
new { myattribute = "something" }) %>
Routing is never associated with the Absolute URL's, it always renders
or deals with the Absolute URL's
However, the Html.RouteLink can take the protocol and domain values to
generate the urls that are absolute as generated by the actionlink
helper methods.
RouteURL API to genertate links from route data instead of using action links
1. <%: Url.RouteUrl(new { controller = "Products", action = "List" }) %>
2. return RedirectToRoute(new { action = "SomeAction", customerId = 456 });
3. <%: Html.RouteLink("Delete",new{action= "Delete", id=item.FirstName })%>
Areas
*****
InboundURL
**********
W.r.to areas, it is found that the areaContext's MapRoute API sets the
namespace of the route inthe DataTokens["Namespaces"] configuration
for the route. Hence, when resolving a URL, the framework searches for
the controller in the Namespaces part of the route definiton and does
not resolve a controller from another area or from the base root
directory.
Outbound URL
************
To facilitate this, it uses the DataTokens["area"] to store the name
of the area.
Links between Areas
*****************
To link between 2 areas, use the area property of the
routevaluedictionary and se tthe are nmae so tha the URL points to the
specified area than the current area.
To jump from the area to the root controllers, we have to provide a
(string)null in the area parameter in the routevaluedictionary.
Each route contains the following info,
1. the url
2. the curly braces that specify the match
3. the constraints for the inputs in the url parameters
Each route should be anything that inherits from the RouteBase.
****************
foreach route in the routescollection do,
{
1. The url in the route should match the incoming url
2. The contents for the curly braces must match in the incoming url
3. The constraints should also match with the route taken from the
routes collection.
4. If a match occurs, then the route is considered as a valid one
}
for every route match to be done, the routebase supplies the URL, the
curlybrace dictionary with its replacement from the request URL, route
parameter values with the optional ones for which no value was
received from the i/p request.
3. The route handler is passed with the requestContext [url, cookies,
authentication data, request data etc]
once a first route match is done, the routing mechanism stops finding
the next match thereafter
The values for the action method parameters are taken from the
RouteData's values. Ex: RouteData.Values["name"] will be used for an
action method like public ActionResult GetUserData(string
name){..........}
To mark a parameter as optional in a route, set the route as follows,
routes.MapRoute("","Catalog/{color}", new {controller="catalog",
action="list", color=(string)null});
Here the (string)null is to specify that a null is used for a string
datatype parameter.
HttpVerbConstraints
*******************
RouteConstraints to restrict HTTPGet an HTTPPost methods,
this can be done via the attributes on the action methods or can be
done in the routing level itself. If done in the routing level, the
constraint is applied at an earlier stage in the pipeline than the
attributes in the action methods.
Constraints
**********
When a constraint failed, then the route next to the that evaluates to
false is evaluated.
sample:
var ieOnlyRoute = new Route("Customer/Edit", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE"),
cookieConstraint = new CookieConstraint()
})
};
Also it is possible to map controllers from a different namespace, sample
To accept any number of segments in the url, use the catchall
parameter in the route config in global.asax as follows,
var ieOnlyRoute = new Route("Customer/Edit/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
}),
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
To enable the file access also to be routed instead of rendering it
dierectly use the following route setting in the global.asax after 1
or more routes are registered there.
routes.RouteExistingFiles = true;
To render the content files only of specific folder the following
settings can be used in the global.asax.cs
routes.RouteExistingFiles = true;
routes.IgnoreRoute("Content/{file}.{abc}");
routes.IgnoreRoute("Content/{*restOfTheUrl}");
The above 2 lines are equivalent to routes.Add(new
Route("Content/{file}.{abc}", new StopRoutingHandler());
********************************************************************************************
Handling the Outgoing URL's
*************************
The way in which the Html.ActionLink renders the url parameters is
based on the routing defitions
Sample1 [w/o explicit routing]
*************************
var ieOnlyRoute = new Route("Customer/Edit/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
//,cookieConstraint = new CookieConstraint()
}),
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
For this routing configuration, the links generated are looking like
<a href="/Customer/Edit?id=firstname">Edit</a>
However, if the above routing configuration is modified to incorporate
the id parameter in the url parameter, the rendered markup will vary
as follows,
var ieOnlyRoute = new Route("Customer/Edit/{id}/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit",
id = UrlParameter.Optional
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
//,cookieConstraint = new CookieConstraint()
}),<%: Html.ActionLink("Click me", "MyAction",
"MyController", "https",
"www.example.com", "anchorName", new { param = "value" },
new { myattribute = "something" }) %>
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
Now, the markup rendered will look like,
<a href="/Customer/Edit/firstname">Edit</a>
This makes the difference and gets the clean url.
To generate the fully qualified URL's, refer the overloads of the
ActionLink method that takes the domain, uri scheme etc to generate a
fully absolute URL.
<%: Html.ActionLink("Click me", "MyAction", "MyController", "https",
"www.example.com", "anchorName", new { param = "value" },
new { myattribute = "something" }) %>
Routing is never associated with the Absolute URL's, it always renders
or deals with the Absolute URL's
However, the Html.RouteLink can take the protocol and domain values to
generate the urls that are absolute as generated by the actionlink
helper methods.
RouteURL API to genertate links from route data instead of using action links
1. <%: Url.RouteUrl(new { controller = "Products", action = "List" }) %>
2. return RedirectToRoute(new { action = "SomeAction", customerId = 456 });
3. <%: Html.RouteLink("Delete",new{action= "Delete", id=item.FirstName })%>
Areas
*****
InboundURL
**********
W.r.to areas, it is found that the areaContext's MapRoute API sets the
namespace of the route inthe DataTokens["Namespaces"] configuration
for the route. Hence, when resolving a URL, the framework searches for
the controller in the Namespaces part of the route definiton and does
not resolve a controller from another area or from the base root
directory.
Outbound URL
************
To facilitate this, it uses the DataTokens["area"] to store the name
of the area.
Links between Areas
*****************
To link between 2 areas, use the area property of the
routevaluedictionary and se tthe are nmae so tha the URL points to the
specified area than the current area.
To jump from the area to the root controllers, we have to provide a
(string)null in the area parameter in the routevaluedictionary.
Comments
Post a Comment