tags:

views:

142

answers:

2

Hello,

I have an object that requires the URL of a file that resides in the root of my web application. If this was an object that inherited from System.Web.Ui.Page I would just use the httpRequest object. However because this object does not I am uncertain how to get this url. Depending on the calling object, the url will be either /something.htm or ~/something.htm

Can someone show me the way? Thanks!

-Nick

+2  A: 

I'm not sure why you'd use HttpRequest for this, but you can use HttpContext.Current.Request, assuming that HttpContext.Current is not null.

John Saunders
Well.. this is where I am not certain. So this is not a code behind object. So I am uncertain how I can instantiate HTTPRequest from within my class.
Nick
That's not instantiation. Instantiation is the creation of an instance of a class. What I showed you doesn't create anything.
John Saunders
I'm aware. But if I wanted to use the HTTPRequest object.. I'd have to have an instance of it. Looking at this class I am uncertain what arguments it requires. Does that make sense?
Nick
Please use the following: "HttpContext.Current.Request". Use it just like that. I wouldn't have told you about it if I didn't expect it to work. I would be embarrassed, and I don't like that. ;-)
John Saunders
Thanks John.. That's got me close. And I think it's the answer. I have been working in that direction. What I have so far: HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);Now I just need to do some string manipulation so I can cut off the path after the virtual directory.. ie www.something/virtualdir/filename.htmGetting real close!
Nick
@John - Your answer deserves a bunch of up votes. You really worked for this one. :)
Ben Griswold
A: 

John's got it right. You can/should use the HttpContext.Current.Request object as he stated. I think you are also looking for the Url up to the root only. In other words, you don't want the page name or query string params if they exist.

This routine is a little obnoxious but it should give you what you need. Notice the reference to HttpContext.Current.Request.

private string UrlUpToRootWithNoPageReferenceOrQueryStringParameters()
{
    string Port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];

    if (Port == null || Port == "80" || Port == "443")
        Port = "";
    else
        Port = ":" + Port;

    string Protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];

    if (Protocol == null || Protocol == "0")
        Protocol = "http://";
    else
        Protocol = "https://";

    return Protocol + Context.Request.ServerVariables["SERVER_NAME"] + Port + Context.Request.ApplicationPath;
}

There are shorter ways to get what you want, but again the routine above will work. If you're interested in more, check out Rick Strahl's Making Sense of ASP.NET Paths for more.

Ben Griswold