2017-05-04 126 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和「你叫什麼名字」

相關問題