How to respect the MVC routes when resolving the URL to an action

casper.rasmussen/ February 26, 2017/ Episerver CMS/ 2 comments

Routing is the way an ASP.NET MVC web application directs a web request to a given controller. ASP.NET MVC and Episerver has a dynamic content map (through routes in a route table) that ensures a given URL – e.g. http://mywebsite.com/article-1 – gets processed by a controller with respect to a specific content instance. It’s all something that’s very fundamental in both platforms.

Some developers are not aware of all the built-in features that enables them to resolve a content URL – e.g. http://mywebsite.com/article-1 – with respect to the current route definition.
You may think, that’s not true.. we always use Episervers UrlResolver to get a content URL. And that’s right – exactly what you need to do. But.. people tend to forget that route tables are more than default content routes. It’s also used for custom segments and actions. The idea is that it’s just as important to respect the route definition when you need to use Episerver’s custom segments or more simply, if you just want to rely on an action within your controller not being Index().

I’ve seen creative solutions, during code reviews, that simply uses assumptions to build the URL for a given action within a controller. An example would like this:

string postUrl = string.Format("{0}/{1}", this._urlResolver.GetUrl(content.ContentLink), "Submit");

It will work.. until the route definition changes. Instead, developers should always use Episervers VirtualPathArguments to resolve the correct URL. It respects your need for a special controller action or any custom segments that you may require.


var postUrl = this._urlResolver.GetUrl(content.ContentLink, ContentLanguage.PreferredCulture.Name,
new VirtualPathArguments()
{
RouteValues = new RouteValueDictionary(new { action = "Submit" })
});

It’s very simple and highly flexible. Enjoy!

2 Comments

  1. Great! does it work if the “submit” is in the blockController?

    1. Hi Luc.

      No – it won’t. Your blocks will not resolve a URL via the UrlResolver. They aren’t represented via a web address.

      Thanks.

      Casper

Leave a Comment

Your email address will not be published. Required fields are marked *

Please type the characters of this captcha image in the input box

Please type the characters of this captcha image in the input box
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
*
*