【问题标题】:Overview of how to rewrite a URL for dynamically generated page?如何为动态生成的页面重写 URL 的概述?
【发布时间】:2015-07-11 08:56:12
【问题描述】:

我正在编写自己的博客系统作为练习练习,我遇到了一个我很难找到答案的问题。

为动态生成的页面定义和实现自定义 URL 的必要步骤是什么?

我真的只是在寻找必要步骤的高级概述。

我知道的:

我需要将此 URL 存储在我的数据库中,因此我需要为我的模型添加一个位置。

PostModel.cs(模型)

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }
    public string IntroText { get; set; }
    public string Body { get; set; }
    public DateTime Created { get; set; }
    public DateTime? Modified { get; set; }
    public string Author { get; set; }
    public List<Comment> Comments { get; set; }
}

所以,假设我已成功将所需的 URL 存储在数据库中,它看起来像这样:

/this-is-a-test-entry/

目前我正在根据他们的 ID 提取我的条目,但我希望能够定义我自己的 URL。我真的不知道从这里开始下一步是什么。 (控制器、路由配置,还有什么?)

有人可以提供我需要采取的后续步骤的高级概述吗?

【问题讨论】:

    标签: c# asp.net-mvc url-rewriting


    【解决方案1】:

    你要做的是开始根据 URL 提取记录(确保你也索引该属性)然后你基本上可以使用默认路由来做:

    public class BlogController
    {
        public ActionResult Post(string id)
        {
            //get the post via URL
        }
    }
    

    然后您可以通过以下导航来访问它:

    http://www.yoursite.com/Blog/Post/this-is-a-test-entry
    

    【讨论】:

    • 这是有道理的。所以基本上当我有一个像“?id = 3”这样的url时,我是通过id请求该记录......我需要做的就是通过我存储的url请求它?
    • @DanBeaulieu 基本上是的,只是你的获取机制需要改变。如果您还没有确保您的 URL 列具有唯一性约束。
    • 哇,这么简单。我期待着今晚回家时尝试这个。但我已经知道这个答案是正确的。谢谢mattommo!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2017-04-14
    • 1970-01-01
    • 2018-07-28
    相关资源
    最近更新 更多