Danny Brady
Danny Brady

Reputation: 1935

MVC Routing - changing routes

Using MVC4, I have the following routing for a blog post detail action which is SEO friendly URLS:

public ActionResult Details(int id, string postName)
{
    BlogPost blogPost = _blogService.GetBlogPostById(id);
    string expectedName = blogPost.Title.ToSeoUrl();
    string actualName = (postName ?? "").ToLower();

    if (expectedName != actualName)
        return RedirectToAction("Details", "Blog", new { id = blogPost.BlogPostId, postName = expectedName });

    var vm = BuildBlogPostDetailViewModel(id);
    return View(vm);
}

The SEO route is constructed using the following helper method:

public static class Helper
{
    public static string ToSeoUrl(this string url)
    {
        // ensure the the is url lowercase
        string encodedUrl = (url ?? "").ToLower();

        // replace & with and
        encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");

        // remove characters
        encodedUrl = encodedUrl.Replace("'", "");

        // remove invalid characters
        encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9]", "-");

        // remove duplicates
        encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");

        // trim leading & trailing characters
        encodedUrl = encodedUrl.Trim('-');

        return encodedUrl;
    }
}

This produces a route like so:

/Blog/Details/1?postName=user-group-2013

What I am trying to achieve is the following route:

/Blog/Details/user-group-2013

Any suggestions on how to achieve and optimize this?

Many Thanks

Upvotes: 1

Views: 217

Answers (2)

Andrey Gubal
Andrey Gubal

Reputation: 3479

You may try to change you routing in RouteConfig class.

Seems you are having there just default route:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

And one more route BEFORE default route:

// This route will return /Blog/Details/1/user-group-2013
routes.MapRoute(
     name: "MyRoute",
     url: "{controller}/{action}/{id}/{postName}",
     defaults: new { controller = "Blog", action = "Details", id = UrlParameter.Optional, postName = UrlParameter.Optional}
            );

// Or this route. It should return /Blog/Details/user-group-2013
routes.MapRoute(
     name: "MyRoute2",
     url: "{controller}/{action}/{postName}",
     defaults: new { controller = "Blog", action = "Details", id = UrlParameter.Optional, postName = UrlParameter.Optional}
            );

Upvotes: 0

Amit
Amit

Reputation: 15387

Try this

return RedirectToAction("Details", "Blog", new { blogPost.BlogPostId,expectedName });

Upvotes: 1

Related Questions