Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VirtualPathUtility.ToAbsolute() VS. Url.Content()

I have been working in an MVC project, and have seen both of these used. I was wondering what the difference between them is? Is it incorrect to use one over the other? My understanding is that I should be using Url.Content(), but VirtualPathUtility.ToAbsolute() seems to be working as well.

like image 387
Ted Ballou Avatar asked Aug 25 '10 15:08

Ted Ballou


2 Answers

Url.Content() is an utility method part of MVC. Being there to uniformize and centralize utility classes I guess.

VirtualPathUtility.ToAbsolute() is a .NET Framework method. Maybe the MVC one is using it, we would have to check the source...

Hope the helps

like image 137
Mike Gleason jr Couturier Avatar answered Nov 15 '22 07:11

Mike Gleason jr Couturier


If you are doing this conversion within a Controller, then I'd favour VirtualParthUtility.ToAbsolute() over Url.Content().

The benefit comes when you want to unit test the controller actions. Rather than call it directly though, I'd define an interface IPathUtilities, say, with one implementation using VirtualPathUtility methods for the live site, and another using some sort of mock when testing.

If you call VirtualPathUtility directly, then you won't be able to test the action method (you might have thought some clever mocking of HttpContext would get round this, but having tried this myself I couldn't find a way to do it).

like image 30
Appetere Avatar answered Nov 15 '22 08:11

Appetere