Asp.net mvc 3 Asp.net MVC3关于URL';s
我正在使用Asp.net MVC制作一个应用程序 我有一个动态生成的url,就像 http:\localhost:4351\username 我想要的功能是,如果用户在地址栏上复制它,它将重定向到一个新地址 像 http:\localhost:4355\users\profile\usernameAsp.net mvc 3 Asp.net MVC3关于URL';s,asp.net-mvc-3,Asp.net Mvc 3,我正在使用Asp.net MVC制作一个应用程序 我有一个动态生成的url,就像 http:\localhost:4351\username 我想要的功能是,如果用户在地址栏上复制它,它将重定向到一个新地址 像 http:\localhost:4355\users\profile\username routes.MapRoute("Route1", "Username", new { controller = "Users", action = "Profile" }); routes.MapR
routes.MapRoute("Route1", "Username", new { controller = "Users", action = "Profile" });
routes.MapRoute("Route2", "Users\Profile\Username", new { controller = "Users", action = "Profile" });
我在其中定义了一个名为users的控制器和一个名为profile的操作
如何实现此功能?您可以将roure添加到Global.asax.cs文件中:
routes.MapRoute(
"UsernameRoute", // Route name
"{username}", // URL with parameters
new { controller = "Home", action = "Redirect" }
);
并将以下操作添加到HomeController:
public ActionResult Redirect(string username)
{
//Check if user exists
bool userExists = true;
if (userExists)
{
return RedirectToAction("Profile", "User", new { id = username });
}
return RedirectToAction("Index");
}
你需要两条地图路线 不清楚您的意思是“用户名”是实际用户名还是URL的一部分。因此,我将展示两种方式: 方法1: 如果路径为文本:http:\localhost:4351\username,则为 和文本路径:http:\localhost:4355\users\profile\username
routes.MapRoute("Route1", "Username", new { controller = "Users", action = "Profile" });
routes.MapRoute("Route2", "Users\Profile\Username", new { controller = "Users", action = "Profile" });
如果用户名是用户的实际名称,请执行以下操作:
方法2:
示例:http:\localhost:4351\mySpecialUsername
和http:\localhost:4351\users\profile\mySpecialUsername
routes.MapRoute("Route1", "{Username}", new { controller = "Users", action = "Profile" });
routes.MapRoute("Route2", "Users/Profile/{Username}", new { controller = "Users", action = "Profile" });
对于方法2,控制器中的操作应如下所示:
// Example
public ActionResult Profile(string Username)
{
return Content(string.Format("Username: {0}", Username));
}
希望有帮助 如何区分您生成的(用户可见的)URL,如“http:\localhost:4351\username”和用户直接在地址栏中输入的URL“http:\localhost:4355\users\profile\username”?生成的URL和用户可见的URL都是相同的,ie我正在显示生成的URL,用户可以将其复制并粘贴到地址栏:)我尝试了您的解决方案,但当我键入http:\\localhost:4351\username时,显示错误消息IControllerFactory“MyApplication.Web.Mvc.SpringControllerFactory”未返回名为“username”的控制器。