2017-05-04 94 views
-3

我在我当前的项目中面临一个问题,我想为我的页面显示自定义URl。我尝试了很多技术,但都没有满足我的要求。 我想URL是这样的:WordPress的博客类型MVC(自定义URL路由)中的固定链接

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

目前,我能够设置URL是这样的:

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

我想从URL忽略查询字符串。这样Controller可以识别请求&做出相应的响应。

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

我的控制器

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

RouteConfig

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

我刚刚注意到,我要像URL StackOverflow的使用

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

我认为这肯定URL解决您的问题,请试试这个标题:http://www.jerriepelser.com/blog/generate-seo-friendly-urls-aspnet-mvc/ – stylishCoder

+0

请参阅[多层次的MVC自定义路由](https://stackoverflow.com/a/31958586/181087)。 – NightOwl888

回答

3

使用属性路由,以包括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的使用观察到的路线。

在生成您的网址的视图中,您可以利用模型生成所需的格式。

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

如何产生的废料

How does Stack Overflow generate its SEO-friendly URLs?

在这里找到答案有了这个,自定义URL看起来就像

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

item与123456的ID和“你叫什么名字”