创建包含 id 和 title slug 的规范 URL

发布于 2024-12-10 10:42:12 字数 456 浏览 0 评论 0原文

我想复制 StackOverflow 对其 URL 所做的事情。

例如:

C# 的隐藏功能? - (C# 的隐藏功能?)

C# 的隐藏功能C#? - (C# 的隐藏功能?)

将带您到同一页面,但当他们返回到浏览器总是返回第一个。

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

I want to replicate what StackOverflow does with its URLs.

For example:

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

or

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

Will Take you to the same page but when they return to the browser the first one is always returned.

How do you implement the change so the larger URL is returned?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

呆萌少年 2024-12-17 10:42:12

我之前处理这个问题的方法是有两个路由,

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

如果我们只有身份证号。我们还通过对照问题标题的 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;
    }
}

The way that I've handled this before is to have two routes, registered in this order

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

now in the controller action,

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

We'll permanently redirect to the URL that contains the title slug (lowercase title with hyphens as separators) if we only have the id. We also make sure that the title passed is the correct one by checking it against the slugged version of the question title, thereby creating a canonical URL for the question that contains both the id and the correct title slug.

A couple of the helpers used

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文