0

我想接受和/User/213123ASP.NET MVC重寫指數行動可選參數

凡是一個參數(user_ID的)

這是我RouteConfig.cs

  routes.MapRoute(
       name: "user", 
       url: "{controller}/{action}/{username}", 
       defaults: new { controller = "User", action = "Index", username = UrlParameter.Optional } 
      ); 

And my UserController.cs

 public ActionResult Index() 
     { 
      ViewData["Message"] = "user index"; 
      return View(); 
     } 

     [Route("user/{username}")] 
     public ActionResult Index(string username) 
     { 
      ViewData["Message"] = "!" + username + "!"; 
      return View(); 
     } 

這適用於.net-core 1.0,但不適用於mvc5。我錯過了什麼?

謝謝

編輯:

剛剛這在我的UserController.cs也不起作用(返回404):

 public ActionResult Index(string username) 
     { 
      if (!String.IsNullOrEmpty(username)) 
      { 
       ViewData["Message"] = "Hello " + username; 
      } 
      else 
      { 
       ViewData["Message"] = "user index"; 
      } 

      return View(); 
     } 

說明:HTTP 404資源您正在查找(或其某個依賴項)可能已被刪除,名稱已更改或暫時不可用。請檢查以下網址並確保它拼寫正確。

請求的URL:/用戶/ ASD

EDIT2:

更新RouteConfig.cs

 routes.MapRoute(
      "userParam", "user/{username}", 
      new { controller = "user", action = "IndexByUsername" }, 
      new { username = @"\w+" } 
     ); 

     routes.MapRoute(
      name: "user", 
      url: "user", 
      defaults: new { controller = "User", action = "Index"} 
     ); 

現在要求IndexByUsername指數作爲用戶名

/User/asd仍然返回404

EDIT4:當前代碼:

RouteConfig.cs:

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

UserController.cs

public class UserController : Controller 
{ 
    public ActionResult Index(string username) 
    { 
     if (!String.IsNullOrEmpty(username)) 
     { 
      ViewData["Message"] = "Hello " + username; 
     } 
     else 
     { 
      ViewData["Message"] = "user index"; 
     } 

     return View(); 
    } 
} 
+0

你只需要'公衆的ActionResult指數(用戶名字符串)'(並檢查是否'username'是否爲null) –

+0

@StephenMuecke請參閱我的編輯 – Cornwell

+1

您的網址是'/ user/asd',它試圖調用'userController'的'asd()'方法 - 它不存在因此是404。需要是'user/index/asd'(或者你可以爲'/ user/{username}'創建一個特定的路由) –

回答

2

你的東東ð只有一個簽名

public ActionResult Index(string username) 

,並在該方法的操作方法,你可以檢查的usernamenull與否。

然後你的路線definitiosn需要爲(注意user路線所需要的默認路由前放置)

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

再次感謝您 – Cornwell