Assuming I understood your problem correctly, here's the solution I propose:
Add the following change to your routing mechanism:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Tutorials",
url: "Tutorials/{id}/{title}",
defaults: new { controller = "Tutorials", action = "Show", title = UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
and then in your Tutorials controller:
public class TutorialsController : Controller
{
// GET: /Tutorials
public ActionResult Index()
{
// here you can display a list of the most recent tutorials or whatever
return View();
}
// GET: /Tutorials/1 (will be redirected to the one below)
// GET: /Tutorials/1/Intro-into-ASP_NET-MVC
public ActionResult Show(int id, string title)
{
string key = string.Format("tutorial-{0}", id.ToString());
Tutorial model = TempData[key] as Tutorial;
// if this is not a redirect
if ( model == null )
{
model = GetTutorial(id);
}
// sanitize title parameter
string urlParam = model.Title.Replace(' ', '-');
// apparently IIS assumes that you are requesting a resource if your url contains '.'
urlParam = urlParam.Replace('.', '_');
// encode special characters like '\', '/', '>', '<', '&', etc.
urlParam = Url.Encode(urlParam);
// this handles the case when title is null or simply wrong
if ( !urlParam.Equals(title) )
{
TempData[key] = model;
return RedirectToAction("Show", new { id = id, title = urlParam });
}
return View(model);
}
private Tutorial GetTutorial(int id)
{
// grab actual data from your database
Tutorial tutorial = new Tutorial { Id = 1, Title = "Intro into ASP.NET MVC" };
return tutorial;
}
}
UPDATE:
the solution presented above will redirect
/Tutorials/1
to
/Tutorials/1/Intro-into-ASP_NET-MVC.
If you actually want to display the action name in the url, like /Tutorials/Show/1/Intro-into-ASP_NET-MVC you can just change the "url" in the "Tutorials" route to url: "Tutorials/Show/{id}/{title}"
.
You can also replace the RedirectToAction with RedirectToRoute("Default", new { id = id, title = urlParam });
which will make sure it matches the route named "Default", but this approach would yield the following url: www.mysite.com/Tutorials/Show/1?title=Intro-into-ASP_NET-MVC