简体   繁体   English

如何从C#App_Code类中获取当前页面的URL?

[英]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, 谢谢,

From your class you can use the HttpContext.Current property (in System.Web.dll). 在您的类中,您可以使用HttpContext.Current属性(在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. 底层对象是一个Page对象,因此如果将其强制转换为该对象,则使用通常在Page对象中使用的任何对象,例如Request属性。

它很脆弱且难以测试,但您可以使用System.Web.HttpContext.Current ,它将为您提供一个Request属性,而该属性又具有RawUrl属性。

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 :) 我试着把它分解一点:)

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? 在过去,我还推出了自己的日志记录类并使用了Console.Writeln(),但实际上已经有很多好的日志记录选项,所以为什么要去那里? I use NLog pretty much everywhere; 我到处都使用NLog ; 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. 它具有非常灵活的各种日志输出目的地,包括控制台和文件,大量的日志格式选项,并且设置与各种.net框架(包括紧凑)的版本是微不足道的。 Running the installer will add NLog config file options to the Visual Studio Add New Item dialog. 运行安装程序会将NLog配置文件选项添加到Visual Studio“ 添加新项”对话框中。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM