C# MVC中Wordpress博客类型Permalink(自定义URL路由)

C# MVC中Wordpress博客类型Permalink(自定义URL路由),c#,asp.net-mvc,asp.net-mvc-routing,custom-url,C#,Asp.net Mvc,Asp.net Mvc Routing,Custom Url,我在当前项目中遇到了一个问题,我想为我的页面显示自定义URl。我尝试了很多技巧,但没有一个能满足我的要求。 我想要这样的URL: http://www.anyDomain.com/What-Is-Your-Name 目前,我可以这样设置URL: http://www.anyDomain.com/What-Is-Your-Name?Id=1 我想忽略URL中的查询字符串。这样控制器可以识别请求并相应地响应 这里,Id用于从数据库中获取详细信息。如何将参数值从视图传递到控制器,使其能够识别请求而

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

http://www.anyDomain.com/What-Is-Your-Name
目前,我可以这样设置URL:

http://www.anyDomain.com/What-Is-Your-Name?Id=1
我想忽略URL中的查询字符串。这样控制器可以识别请求并相应地响应

这里,
Id
用于从数据库中获取详细信息。如何将参数值从
视图
传递到
控制器
,使其能够识别请求而无需将其添加到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 })">

使用属性路由包括
id
标题
,控制器可以如下所示

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() })">
在这里找到了如何生成slug的答案

这样,自定义URL看起来就像

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

对于ID为123456、标题为“What Is Your Name”的
项目

我认为此url肯定能解决您的问题,请尝试以下方法:参见。
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();
    }
}