Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

url

asp.net

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,

like image 656
Justin808 Avatar asked Oct 19 '10 22:10

Justin808


3 Answers

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

  • Request
  • Url and RawUrl

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.

like image 167
Rebecca Chernoff Avatar answered Oct 05 '22 01:10

Rebecca Chernoff


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.

like image 34
blowdart Avatar answered Oct 05 '22 03:10

blowdart


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 :)

like image 24
Robert Avatar answered Oct 05 '22 01:10

Robert