代码之家  ›  专栏  ›  技术社区  ›  Tom Gullen

使用ASP.NET检索域名和路径

  •  1
  • Tom Gullen  · 技术社区  · 14 年前

    我需要从请求中获取域名和路径,以提供以下返回值:

    domain1.com/default.aspx    returns      domain1.com/default.aspx
    domain1.com/                returns      domain1.com/
    domain1.com                 returns      domain1.com
    

    目前,我尝试的每个URL获取函数似乎都会返回 domain.com/default.aspx 不管我浏览器中的地址栏是什么。有什么解决办法吗?

    我尝试了许多不同的内置函数来检索部分请求,但似乎没有一个函数提供所需的结果。

    4 回复  |  直到 8 年前
        1
  •  1
  •   Mike Hofer    14 年前

    你的问题有解决办法。

    HttpContext.Current.Request.Url 将返回 Uri 对象,该对象包含为您细分的URL的所有部分。从中,你应该能够得到你想要的。具体来说,你想要的财产是 Uri.Authority .

    编辑:尝试如下操作:

        public static string GetPath(this HttpRequest request)
        {
            var authority = request.Url.Authority;
            var pathAndQuery = request.Url.PathAndQuery;
            var query = request.Url.Query;
            var path = pathAndQuery.Substring(0, 
                           pathAndQuery.Length - query.Length));
    
            if (!authority.EndsWith("/"))
                authority += "/";
    
            return authority + path;
        }
    
        2
  •  0
  •   Kane    14 年前

    您可能希望在IIS中为您的域设置一个具有多个绑定/主机头的网站,然后删除 阿斯克斯 来自默认文档。你 应该 然后可以使用 urlMappings 配置元素以方便重定向。如果您需要更多有关URL映射的信息,请查看此链接: http://dotnetperls.com/urlmappings-aspnet

        3
  •  0
  •   Jonathan Nesbitt    14 年前

    您可以为每个域创建一个httpmodule-实现应用程序“BeginRequest”事件,如下所示:

    private void Application_BeginRequest(object source, EventArgs e)
    {
        // get context and file path
        HttpContext context = ((HttpApplication)source).Context;
        string filePath = context.Request.FilePath;
    
        if (filePath.Equals("/"))
        {
            // redirect to products page
            context.Response.Redirect(filePath + "products.aspx");
        }
    }
    

    这应该重定向 http://www.domain1.com/ http://www.domain1.com/products.aspx -请求 http://www.domain1.com/default.aspx 不应重定向。

        4
  •  -1
  •   Prashant Lakhlani    14 年前

    请在IIS中提供默认文档,它将以您希望的方式工作。所以你可以设定 products.aspx 在里面 domain1.com 的默认文档 domain2.com 成功 categories.aspx 一切准备就绪。