I’ve been writing a little program that has to get some information from a diagnostic page on an embedded device. There is no password configured, but you still have to go through the login page to get a session. The device uses the rather antiquated “HTML refresh” method of redirecting from the login page to the page you originally requested.
The redirection is in the form of a relative url, ie “../../diagnostics/streams.cgi“. I needed to convert this into an absolute path to make the next request.
This is not ASP.NET, just a plain old windows forms app, so I’m using HttpWebRequest and can’t use the normal ASP.NET tools for dealing with the paths. I could just hard code it in this situation, but I hate doing that. I knew that had to be a “correct” way of dealing with it. Eventually I found out about the System.Web.VirtualPathUtility class and I thought I was home and dry. It appeared that the VirtualPathUtility.toAbsolute(VirtualPath, ApplicationPath) was what I needed. However, that doesn’t seem accept relative paths that take you back to the root. I kept getting the error “The relative virtual path ../../diagnostics/streams.cgi is not allowed here”. No indication of why – just that it’s not allowed.
Finally I spotted the VirtualPathUtility.Combine(absolutePath, relativePath) method. This was what actually worked for me:
(request is the original HttpRequest that returned the redirect)
String url = VirtualPathUtility.Combine(request.RequestUri.AbsolutePath, redirectUrl);
I hope this will help someone as my Googling revealed that a lot of people had given up looking for this and had hand-crafted their own solutions to the problem.