创建规范URL,包括id和title slug

时间:2011-10-17 21:45:59

标签: asp.net-mvc-3 seo asp.net-mvc-routing http-status-code-301

我想复制StackOverflow对其URL的作用。

例如:

Hidden Features of C#? - (Hidden Features of C#?

Hidden Features of C#? - (Hidden Features of C#?

将您带到同一页面,但当他们返回浏览器时,将始终返回第一页。

如何实施更改以便返回更大的网址?

1 个答案:

答案 0 :(得分:4)

之前我处理过的方法是有两条路线,按此顺序登记

routes.MapRoute(
    null,
    "questions/{id}/{title}",
    new { controller = "Questions", action = "Index" },
    new { id = @"\d+", title = @"[\w\-]*" });

routes.MapRoute(
    null,
    "questions/{id}",
    new { controller = "Questions", action = "Index" },
    new { id = @"\d+" });

现在在控制器动作中,

public class QuestionsController 
{
    private readonly IQuestionRepository _questionRepo;

    public QuestionsController(IQuestionRepository questionRepo)
    {
        _questionRepo = questionRepo;
    }

    public ActionResult Index(int id, string title)
    {
        var question = _questionRepo.Get(id);

        if (string.IsNullOrWhiteSpace(title) || title != question.Title.ToSlug())
        {
            return RedirectToAction("Index", new { id, title = question.Title.ToSlug() }).AsMovedPermanently();
        }

        return View(question);
    }
}

如果我们只有id,我们将永久重定向到包含标题slug的URL(带有连字符的小写标题作为分隔符)。我们还通过检查问题标题的slugged版本来确保传递的标题是正确的,从而为包含id和正确标题slug的问题创建一个规范URL。

使用了几个助手

public static class PermanentRedirectionExtensions
{
    public static PermanentRedirectToRouteResult AsMovedPermanently
        (this RedirectToRouteResult redirection)
    {
        return new PermanentRedirectToRouteResult(redirection);
    }
}

public class PermanentRedirectToRouteResult : ActionResult
{
    public RedirectToRouteResult Redirection { get; private set; }
    public PermanentRedirectToRouteResult(RedirectToRouteResult redirection)
    {
        this.Redirection = redirection;
    }
    public override void ExecuteResult(ControllerContext context)
    {
        // After setting up a normal redirection, switch it to a 301
        Redirection.ExecuteResult(context);
        context.HttpContext.Response.StatusCode = 301;
        context.HttpContext.Response.Status = "301 Moved Permanently";
    }
}

public static class StringExtensions
{
    private static readonly Encoding Encoding = Encoding.GetEncoding("Cyrillic");

    public static string RemoveAccent(this string value)
    {
        byte[] bytes = Encoding.GetBytes(value);
        return Encoding.ASCII.GetString(bytes);
    }

    public static string ToSlug(this string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return string.Empty;
        }

        var str = value.RemoveAccent().ToLowerInvariant();

        str = Regex.Replace(str, @"[^a-z0-9\s-]", "");

        str = Regex.Replace(str, @"\s+", " ").Trim();

        str = str.Substring(0, str.Length <= 200 ? str.Length : 200).Trim();

        str = Regex.Replace(str, @"\s", "-");

        str = Regex.Replace(str, @"-+", "-");

        return str;
    }
}