2017-09-14 191 views
0

我試圖讓我的網站看起來很好,並與slu se友好。我想我已經成功了,但後來我的默認路由停止工作。 當我去這個example.com/location/viewlocation/528然後url結束像example.com/528/a-nice-location使用slug和id的MVC url路由。使默認路由混亂

所以,這很好! 但現在我的正常東西dosent工作。 打字在錯誤example.com/home/index結果

參數字典包含參數非空類型「System.Int32」的「ID」爲方法「System.Web.Mvc一個空條目在'Oplev.Controllers.LocationController'中的.ActionResult ViewLocation(Int32,System.String)'。可選參數必須是引用類型,可爲空類型,或者聲明爲可選參數。

我已經嘗試了不同的解決方案,但我失去了一些東西。無法讓它工作。

我的代碼: RouteConfig

routes.MapRoute(
      name: "view_location", 
      url: "{id}/{slug}", 
      defaults: new { controller = "Location", action = "ViewLocation", id = UrlParameter.Optional, slug = UrlParameter.Optional } 
     ); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 

位置控制器

public ActionResult ViewLocation(int id, string slug) 
    { 
     if (string.IsNullOrEmpty(slug)) 
     { 
      slug = "a-nice-location"; // testing.. 
      return RedirectToRoute("view_location", new { id = id, slug = slug }); 
     } 
     return View(); 
    } 

Home控制器

public ActionResult Index() 
{ 
    return View(); 
} 

回答

0

好吧,所以我不知何故結束了一些工作! 更改路由的view_location這樣:

  routes.MapRoute(
      name: "view_location", 
      url: "{id}/{slug}", 
      defaults: new { controller = "Location", action = "ViewLocation", slug = UrlParameter.Optional}, 
      constraints: new { id = @"\d+" } 
     ); 
+0

在必要Route屬性或者你可以使用'INT?'類型,而不是'int'。該消息很簡單:如果您使用的是非空類型,則需要爲路由聲明數值約束。 –

1

你的第一個路由匹配網址中包含0,1或2段東西。例如,它匹配../Home/Index。你需要一些方法來區分,例如,你可以把它

routes.MapRoute(
    name: "view_location", 
    url: "ViewLocation/{id}/{slug}", 
    defaults: new { controller = "Location", action = "ViewLocation", slug = UrlParameter.Optional } 
); 

,或者你可以添加一個路由約束

還請注意,只有最後一個參數可以被標記爲UrlParameter.Optional,但在你的情況下, id不是可選的

0

這是爲了補充已經給出的答案。具有路由約束的屬性路由也適用。

首先確保屬性的路由在RouteConfig

//Attribute routing 
routes.MapMvcAttributeRoutes(); // placed before convention-based routes 

//convention-based routes 
routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 

啓用接着使用控制器

[HttpGet] 
[Route("{id:int}/{*slug?}", Name = "view_location")] // Matches GET 528/some-nice-location 
public ActionResult ViewLocation(int id, string slug) { 
    if (string.IsNullOrEmpty(slug)) { 
     slug = "a-nice-location"; // testing.. 
     return RedirectToRoute("view_location", new { id = id, slug = slug }); 
    } 
    return View(); 
}