Truncating Query String & Returning Clean URL C# ASP.net

后端 未结 7 1852
遥遥无期
遥遥无期 2020-12-25 10:11

I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole applicatio

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-25 10:24

    This may look a little better.

        string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);
    
        if (rawUrl.Contains("/post/"))
        {
            bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
    
            if (hasQueryStrings)
            {
                Uri uri = new Uri(rawUrl);
                rawUrl = uri.GetLeftPart(UriPartial.Path);
    
                HtmlLink canonical = new HtmlLink();
                canonical.Href = rawUrl;
                canonical.Attributes["rel"] = "canonical";
                Page.Header.Controls.Add(canonical);
            }
        }
    

    Followed by a function to properly fetch the application URL.

    Works perfectly.

提交回复
热议问题