我想接受和/User/213123
ASP.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();
}
}
你只需要'公衆的ActionResult指數(用戶名字符串)'(並檢查是否'username'是否爲null) –
@StephenMuecke請參閱我的編輯 – Cornwell
您的網址是'/ user/asd',它試圖調用'userController'的'asd()'方法 - 它不存在因此是404。需要是'user/index/asd'(或者你可以爲'/ user/{username}'創建一個特定的路由) –