ASP.NET MVC SEO友好URL

时间:2012-06-23 21:41:08

标签: asp.net-mvc seo asp.net-mvc-routing

我正在尝试关注此页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);
    }
}

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

这是从AccountController的Login操作返回的,

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

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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

请注意,您使用MapRoute而不是MapHttpRoute,因此您希望使用RedirectToRoute或(在标记中)@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}
  }
);