Question

I tried searching Google and Stack Exchange for an answer to this question, and while it did yield some documentation on the Href() method (documentation I have seen before), It seems that questions on this method are either very obscure or nonexistent, and I am still left puzzled about why/when to really use it.

MSDN Documentation: http://msdn.microsoft.com/en-us/library/system.web.webpages.webpageexecutingbase.href(v=vs.111).aspx

I can tell, through this documentation, that it builds an absolute url from a relative path.

My questions are:

  1. Why should I need to do this?
  2. Shouldn't a relative path work fine outside of the testing environment and even on the web server?
  3. Should I change EVERY one of the relative paths in my site to incorporate the Href() method? (Example: Change Context.RedirectLocal("~/") to Context.RedirectLocal(Href("~/")))
  4. What's the best practices for use with this method considering an ASP.NET web-pages environment?

I apologize for being so confused over what seems to be such a simple thing, but I would hate to get my website live only to find out that it was broken or had security holes (first impressions can be a killer).

Was it helpful?

Solution

You would use the method explicitly if you are working with Web Pages 1 and want to ensure that your virtual paths always map correctly to an absolute url. From Web Pages 2, the Href method is called by the framework if the parser encounters a tilde (~) in a url in your cshtml file e.g.

<script type="text/javascript" src="~/Scripts/jquery.js"></script>

When might a path not resolve correctly without using the Href method explicitly or tilde? It might not work if your site's root path structure changes if you change hosting for example. It also might not work if your internal folder structure changes, or if you move files about. If that is unlikely to happen, you probably don't need to worry about using the method. I didn't tend to use it until the Href method was replaced by the tilde. Now I always use it on the basis that it is so much easier to use, and I would prefer to add one additional keystroke to each url than be sorry at some stage in the future.

You can find out more about Href about half way down this page: http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top