【问题标题】:Wordpress Blog type Permalink in MVC(Custom URL Routing)MVC 中的 Wordpress 博客类型永久链接(自定义 URL 路由)
【发布时间】:2017-10-02 03:54:45
【问题描述】:

我在当前项目中遇到了一个问题,我想为我的页面显示自定义 URL。我尝试了很多技术,但没有一个能满足我的要求。 我想要这样的网址:

http://www.anyDomain.com/What-Is-Your-Name

目前,我可以这样设置 URL:

http://www.anyDomain.com/What-Is-Your-Name?Id=1

我想忽略来自 URL 的查询字符串。这样控制器就可以识别请求并做出相应的响应。

这里,Id 用于从数据库中获取详细信息。如何将参数值从View 传递到Controller,这样它就可以在不添加 URL 的情况下识别请求?

我的控制器

[Route("~/{CategoryName}")]
public ActionResult PropertyDetails(int Id)
{
}

路由配置

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults:
    new
    {
        controller = "Home",
        action = "Index",

    }
);

我的观点

<a href="@Url.Action("PropertyDetails", "Home", new {@Id=item.ID,@CategoryName = Item.Title })">

我刚刚注意到,我想要像 StackOverflow 这样的 URL 正在使用

http://stackoverflow.com/questions/43774917/wordpress-blog-type-permalink-in-mvccustom-url-routing

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-routing custom-url


【解决方案1】:

使用属性路由包含idtitle,控制器可以如下所示

public class HomeController : Controller {
    [HttpGet]
    [Route("{id:int}/{*slug}")] //Matches GET 43774917/wordpress-blog-type-permalink-in-mvccustom-url-routing
    public ActionResult PropertyDetails(int id, string slug = null) {
        //...code removed for brevity
    }

    //...other actions
}

这将匹配类似于您观察到的路由与 StackOverflow 正在使用的路由。

在生成 url 时的视图中,您可以利用模型来生成您想要的格式。

<a href="@Url.Action("PropertyDetails", "Home", new { @id=item.ID, @slug = item.Title.ToUrlSlug() })">

ToUrlSlug() 可以作为扩展方法将模型标题转换为您想要的格式word-word-word

public static class UrlSlugExtension {

    public static string ToUrlSlug(this string value) {
        if (string.IsNullOrWhiteSpace(value)) return string.Empty;
        //this can still be improved to remove invalid URL characters
        var tokens = value.Trim().Split(new char[] {  ' ', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);

        return string.Join("-", tokens).ToLower();
    }
}

在此处找到有关如何生成 slug 的答案

How does Stack Overflow generate its SEO-friendly URLs?

这样,自定义 URL 将类似于

http://www.yourdomain.com/123456/what-is-your-name

对于 ID 为 123456 且标题为“你叫什么名字”的item

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    相关资源
    最近更新 更多