自动生成一个典型的web应用MVC3 [英] Generating an canonical automatically for mvc3 webapplication

查看:103
本文介绍了自动生成一个典型的web应用MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用规范的网址在我的网站。我读了互联网上关于它的一些东西,但是我正在寻找一个解决方案,我运行时和在HTML的code添加返回给浏览器,它会自动生成规范。

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 me runtime and add it in the html-code returned to the browser.

我已经发现使用属性在互联网上的例子,但是这不是我要找的。使用属性我仍然决定哪些网页应该得到一个规范的或不是我自己,我希望每一个页面有一个自动生成的。我把它应该有(现有的)解决方案?我挣扎找到一个很好的例子,去努力,所以任何帮助是AP preciated。

I've already found an example on the internet using an attribute, but this is not what i'm looking for. Using an attribute i'm still deciding which page should get an canonical or not myself, I want every page to have one generated automatically. I take it there should be (existing) solutions? I'm struggling finding an good example to work on, so any help is appreciated.

推荐答案

有关剃须刀:

我做了一个扩展方法的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));
}

要获取当前网址

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));
}

上调用的Razor视图:

Calling on Razor View:

@Html.CanonicalUrl()

这篇关于自动生成一个典型的web应用MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆