从全局asax获取完整的URL到页面

Ser*_*rge 2 c# asp.net global-asax

我想从全球的asax中检索我的网站的网址.此网址必须完整(协议,域名等).有一个简单的方法吗?

我试过VirtualPathUtility.ToAbsolute但它只给出一个相对路径.

Roy*_*mir 10

试试这个 :

HttpContext.Current.Request.Url.OriginalString
Run Code Online (Sandbox Code Playgroud)

这样您就可以从全局asax访问URL.

Ps你可以通过调试自己完成:

在此输入图像描述

  • OriginalString使用因为你想要完整的原产地信息.

  • 你也可以使用没有端口的那个AbsoluteURI

  • 它给出了一个错误,说"请求在此上下文中不可用". (2认同)

小智 5

您可以通过在 Global.asax 和 HttpApplication.Context.Request.Url 中使用 Application_BeginRequest 方法来实现这一点。请记住,该方法将针对每个请求触发。

public class Global : System.Web.HttpApplication
{
    private void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
    }

    void Application_BeginRequest(Object source, EventArgs e)
    {
        var app = (HttpApplication)source;
        var uriObject = app.Context.Request.Url;
        //app.Context.Request.Url.OriginalString
    }

    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs on application error
    }

    private void RegisterRoutes(RouteCollection routes)
    {
        // Code that runs on register routes
    }
}
Run Code Online (Sandbox Code Playgroud)