1

我正在尝试关注此页面http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx这就是我在 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);
    }
}

成员控制器,

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);
    }

这是从 AccountController 的登录操作返回的,

return RedirectToAction("Index", "Member", new { id = user.UserId, pseudoName = user.PseudoName });

当重定向发生时,Url 最终看起来像http://site.com/Member/1?pseudoName=CEO

我究竟做错了什么?

4

1 回答 1

0

请记住,您正在使用MapRouteover MapHttpRoute,因此您想使用RedirectToRouteor (in the markup)来调用它@Html.RouteLink

因此,要使其在您的上述代码中工作,而不是重定向到一个操作,然后指定参数,请使用以下命令:

return RedirectToRoute("Member", new {
  userId = user.Id, // note i use userId as it's in the route's url
  pseudoName = user.pseudoName
});

此外,您的路线中的修复将如下所示:

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}
  }
);
于 2012-06-23T21:52:15.680 回答