Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC SEO URL

My goal is to have the url routing as following:

http://www.abc.com/this-is-peter-page

http://www.abc.com/this-is-john-page

What is the simplest way to achieve this without placing controller name an function name in the url above? If page above not found, I should redirect to 404 page.

Addon 1: this-is-peter-page and this-is-john-page is not static content, but is from database.

like image 526
Ervin Ter Avatar asked Jul 02 '09 06:07

Ervin Ter


2 Answers

Similar to KingNestor's implementation, you can also do the followings which will ease your work:

1) Write Your Model

public class MyUser{public String UserName{get; set;}}

2) add route to global asax

routes.MapRoute(
   "NameRouting",
   "{name}",
   new { controller = "PersonalPage", action = "Index", username="name" });

3) Roll your own custom model binder derived from IModelBinder

public class CustomBinder : IModelBinder
    {
       public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
       {
          var request = controllerContext.HttpContext.Request;
          var username = getUserNameFromDashedString(request["username"]);
          MyUser user = new MyUser(username);

          return user;
       }
    }

4) in your action:

public ActionResult Index([ModelBinder(typeof(CustomBinder))] MyUser usr)
{
    ViewData["Welcome"] = "Viewing " + usr.Username;
    return View();
}
like image 75
ercu Avatar answered Sep 30 '22 12:09

ercu


I personally wouldn't suggest a route like that but if it meets your needs you need to do something like:

Have the following route in your Global.asax file:

    routes.MapRoute(
       "NameRouting",
       "{name}",
       new { controller = "PersonalPage", action = "routeByName" });

Then, in your "PersonalPageController", have the following method:

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult routeByName(string name)
    {
         switch (name)
         {
             case "this-is-peter-page": return View("PeterView");
             case "this-is-john-page": return View("JohnView");
             case Default: return View("NotFound");
         }
    }

Make sure you have the appropriate views: "PeterView", "JohnView" and "NotFound" in your Views/PersonalPage/.

like image 29
KingNestor Avatar answered Sep 30 '22 14:09

KingNestor