Justin808
Justin808

Reputation: 21512

How can I get the URL of the current page from within a C# App_Code class?

I have a logging class that, well, logs things. I would like to add the ability to automatically have the current page be logged with the messages.

Is there a way to get the information I'm looking for?

Thanks,

Upvotes: 5

Views: 7807

Answers (4)

David Clarke
David Clarke

Reputation: 13256

In the past I've also rolled my own logging classes and used Console.Writeln() but really there are a number of good logging options that already exist so why go there? I use NLog pretty much everywhere; it is extremely flexible with various log output destinations including console and file, lots of log format options, and is trivial to set up with versions targeting the various .net frameworks including compact. Running the installer will add NLog config file options to the Visual Studio Add New Item dialog. Using in your code is simple:

// declare in your class
private static Logger logger = LogManager.GetCurrentClassLogger();

...

// use in your code
logger.Debug(() => string.Format("Url: {0}", HttpContext.Current.Request.Url));

Upvotes: 0

Robert
Robert

Reputation: 1159

public static class MyClass
{
    public static string GetURL()
    {
        HttpRequest request = HttpContext.Current.Request;
        string url = request.Url.ToString();
        return url;
    }
}

I tried to break it down a little :)

Upvotes: 1

Rebecca Chernoff
Rebecca Chernoff

Reputation: 22605

From your class you can use the HttpContext.Current property (in System.Web.dll). From there, you can create a chain of properties:

The underlying object is a Page object, so if you cast it to that, then use any object you would normally use from within a Page object, such as the Request property.

Upvotes: 6

blowdart
blowdart

Reputation: 56500

It's brittle and hard to test but you can use System.Web.HttpContext.Current which will give you a Request property which in turn has the RawUrl property.

Upvotes: 2

Related Questions