I'm trying to follow this page http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx and this is what I have in global.asax,
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"MemberRoute", // routeName
"member/{userId}/{pseudoName}", // url
new
{ // url defaults
controller = "Member",
action = "Index",
userId = 0,
pseudoName = UrlParameter.Optional
},
new
{ // url constraints
userId = @"\d+" // must match url {userId}
}
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
MemberController,
public ActionResult Index(int id, string pseudoName)
{
User user;
var unitOfWork = new UnitOfWork();
user = unitOfWork.UserRepository.GetById(id);
var expectedName = user.PseudoName.ToSeoUrl();
var actualName = (pseudoName ?? "").ToLower();
// permanently redirect to the correct URL
if (expectedName != actualName)
return RedirectToActionPermanent("Index", "Member", new { id = user.UserId, pseudoName = expectedName });
return View(user);
}
This is returned from the Login action from the AccountController,
return RedirectToAction("Index", "Member", new { id = user.UserId, pseudoName = user.PseudoName });
When the redirect takes place, the Url ends up looking like http://site.com/Member/1?pseudoName=CEO
What am I doing wrong?
Keep in mind you're using MapRoute
over MapHttpRoute
, so you want to call it using RedirectToRoute
or (in the markup) @Html.RouteLink
.
So, to make it work in your above code, instead of redirecting to an action, then specifying the parameters, use the following:
return RedirectToRoute("Member", new {
userId = user.Id, // note i use userId as it's in the route's url
pseudoName = user.pseudoName
});
Also, a fix in your route would go as follows:
routes.MapRoute(
"Member", // routeName
"member/{userId}/{pseudoName}", // url
new { // url defaults
controller = "Member",
action = "Index",
userId = 0,
pseudoName = UrlParameter.Optional
},
new { // url constraints
userId = @"\d+" // must match url {userId}
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.