Generating an canonical automatically for mvc3 webapplication

前端 未结 4 1342
生来不讨喜
生来不讨喜 2021-02-04 08:05

I want to use canonical url\'s in my website. I read a few things about it on the internet, but i\'m looking for a solution which will automatically generate the canonical for m

4条回答
  •  情深已故
    2021-02-04 08:17

    For Razor:

    I made one extension method for HtmlHelper:

    public static MvcHtmlString CanonicalUrl(this HtmlHelper html, string path)
    {
        if (String.IsNullOrWhiteSpace(path))
        {
            var rawUrl = html.ViewContext.RequestContext.HttpContext.Request.Url;
            path = String.Format("{0}://{1}{2}", rawUrl.Scheme, rawUrl.Host, rawUrl.AbsolutePath);
        }
    
        path = path.ToLower();
    
        if (path.Count(c => c == '/') > 3)
        {
            path = path.TrimEnd('/');
        }
    
        if (path.EndsWith("/index"))
        {
            path = path.Substring(0, path.Length - 6);
        }
    
        var canonical = new TagBuilder("link");
        canonical.MergeAttribute("rel", "canonical");
        canonical.MergeAttribute("href", path);
        return new MvcHtmlString(canonical.ToString(TagRenderMode.SelfClosing));
    }
    

    To get current URL

    public static MvcHtmlString CanonicalUrl(this HtmlHelper html)
    {
        var rawUrl = html.ViewContext.RequestContext.HttpContext.Request.Url;
    
        return CanonicalUrl(html, String.Format("{0}://{1}{2}", rawUrl.Scheme, rawUrl.Host, rawUrl.AbsolutePath));
    }
    

    Calling on Razor View:

    @Html.CanonicalUrl()
    

提交回复
热议问题