Mixing SEO urls with normal routing in Asp.Net using a custom RouteHandler

1. oktober 2012 20:24 by admin in
On a project I was working on we would like to have URLs like

www.thesite.com/greatproduct

Since this was a MVC 3 site the normal routing like this should work as well.

www.thesite.com/product/details/4

To make this work I was inspired bu the article of Lars-Erik Kindblad. In his article he defines a very greedy route that catches all: 

routes.MapRoute("Friendly", "{*FriendlyUrl}").RouteHandler = new FriendlyUrlRouteHandler();


This breaks the default MVC route defined like this

routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Product", action = "Index", id = UrlParameter.Optional},
                new[] {"thesite.Web.Controllers"} // Parameter defaults
                );

Since both routes are catch all mixing them was not an option. But what about override the functionality of the default route handler? This is very easy. Basically by subclassing MvcRouteHandler we can add custom routing as well :) My custom routehandler does a lookup in the product table to find a product of that name and then show the details for that product. If the product name is not found the normal functionality is 'restored'. Also I do a check to see if the name is not a controller name. So the url www.thesite.com/product still maps to the index method of my product controller even if some product's name is 'product'.
     public class FriendlyUrlRouteHandler : System.Web.Mvc.MvcRouteHandler
{
private static IList<string> controllerNames;private static IList<string> ControllerNames
{
get
{
if (controllerNames == null)
{
controllerNames = Assembly.GetExecutingAssembly().GetTypes().
Where(t => typeof(Controller).IsAssignableFrom(t)).
Select(c=>c.Name.Replace("Controller","")).
ToList();
}
return controllerNames;
}
}
protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
{
var friendlyUrl = (string)requestContext.RouteData.Values["controller"];
var firstPart = friendlyUrl.Contains("/")? 
friendlyUrl.Split('/')[0] : 
friendlyUrl;//it's a controller..handle normally
if (ControllerNames.Contains(firstPart))
{
return base.GetHttpHandler(requestContext);
}
if (!string.IsNullOrEmpty(friendlyUrl))
{
using (var ctx = new SiteDbContext())
{
                    var product = ctx.Events.FirstOrDefault(p => p.Title == friendlyUrl);
 if (product != null)
{
requestContext.RouteData.Values["controller"] = "product";
requestContext.RouteData.Values["action"] = "details";
requestContext.RouteData.Values["id"] = product.Id;
}
}
}
return base.GetHttpHandler(requestContext);
}
}

Handmade Jewelry 12-10-2013 22:42:32 United States #
Handmade Jewelry

wohh  precisely  what I was looking  for,  thankyou  for  putting up.

Copper Jewelry 14-10-2013 03:06:22 United States #
Copper Jewelry

Hi there, just became alert to your blog by way of Google, and discovered that it is genuinely informative. I'm going to watch out for brussels. I’ll be grateful in the event you continue this in future. Lots of men and women will probably be benefited from your writing. Cheers!

Handmade Jewelry 14-10-2013 20:15:41 United States #
Handmade Jewelry

There is noticeably a bundle to discover out about this. I assume you created certain nice factors in options also.

Perruci 21-10-2013 07:52:37 United States #
Perruci

I am really impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it is rare to see a nice blog like this one nowadays..

Copper Jewelry 23-10-2013 20:31:26 United States #
Copper Jewelry

I'm typically to blogging and i genuinely appreciate your posts. The content has truly peaks my interest. Let me bookmark your web web site and sustain checking for brand spanking new data.

Handmade Jewelry 3-11-2013 04:09:50 United States #
Handmade Jewelry

you’ve got an crucial weblog correct here! would you wish to make some invite posts on my weblog?

Allena Borseth 7-11-2013 09:47:10 United States #
Allena Borseth

hello, I would like to share my page dedicated to health http://gourmetreceetas.es

Work Gloves 12-11-2013 08:06:12 United States #
Work Gloves

Hi partner, I would like to share with you how your post was helpful for me. We were capable of take the knowledge you actually so generously created as well as put it to use. Your blog article seriously aided me and that i would like to tell your committed subscribers they genuinely have some one who has her or his mind right. Thanks a lot once more for this amazing post. I've truly saved it on my favored on-line bookmarking site and I recommend everybody else do the exact same.

Sunni Norales 12-11-2013 14:08:07 United States #
Sunni Norales

I saw a noticeable improvement in battery life by disabling Bluetooth, I don't use it so why let it drain?

buy 2000 Twitter followers for $1 20-11-2013 14:05:57 United States #
buy 2000 Twitter followers for $1

I am perpetually thought about this, regards for putting up.

Evon Donnellon 20-11-2013 22:11:31 United States #
Evon Donnellon

There is noticeably a bundle to know about this. I assume you made certain nice points in features also.

agree with 27-11-2013 04:19:38 United States #
agree with

Just  wanna  input on few general things, The website  pattern  is perfect, the  subject material  is  real  good  : D.

SEO ZEN Review 3-12-2013 14:52:04 United States #
SEO ZEN Review

I delight in, cause I discovered just what I was having a look for. You've ended my four day lengthy hunt! God Bless you man. Have a nice day. Bye

Santa Call 5-12-2013 23:39:41 United States #
Santa Call

Admiring the commitment you put into your site and in depth information you present. It's great to come across a blog every once in a while that isn't the same out of date rehashed material. Excellent read! I've saved your site and I'm adding your RSS feeds to my Google account.

Marine 12-12-2013 18:19:43 United States #
Marine

Howdy! This is my first comment here so I just wanted to give a quick shout out and tell you I truly enjoy reading through your posts. Can you suggest any other blogs/websites/forums that cover the same subjects? Thanks!

injury attorney austin 1-1-2014 20:53:31 United States #
injury attorney austin

Did you develop this web web-site your self? You should reply again as I am hoping to generate my very own own web page

Dental Insurance Fraud 19-1-2014 08:33:41 United States #
Dental Insurance Fraud

This is getting a little crowded!

Dental Insurance Fraud 20-1-2014 06:56:12 United States #
Dental Insurance Fraud

This is getting a little crowded!

article 31-1-2014 00:04:55 United States #
article

One more thing to say is that an online business administration training is designed for college students to be able to without problems proceed to bachelor's degree education. The 90 credit education meets the lower bachelor education requirements then when you earn your own associate of arts in BA online, you will get access to the modern technologies on this field. Several reasons why students need to get their associate degree in business is because they may be interested in the field and want to get the general knowledge necessary prior to jumping in to a bachelor diploma program. Thanks for the tips you actually provide within your blog.

Vasiliki 6-2-2014 07:46:33 United States #
Vasiliki

I love your presentation, keep writing an providing information like this.

lokalizacja domeny 8-2-2014 08:22:36 United States #
lokalizacja domeny

I miss Sportsmans Warehouse. That place was an incredible fishing store far ahead of Cabelas as far as a fishing departmet.

crystal 23-2-2014 18:46:00 United States #
crystal

Nice to see information that can help me is still online.

Cortney 25-2-2014 07:43:38 United States #
Cortney

Thanks for your imput, hope to read more from you good job.

breaking News 28-2-2014 00:59:31 United States #
breaking News

Appreciating the time and effort you put into your website and in depth information you offer. It's great to come across a blog every once in a while that isn't the same out of date rehashed information. Wonderful read! I've saved your site and I'm adding your RSS feeds to my Google account.

Michelina 1-3-2014 12:29:50 United States #
Michelina

Nice work your blog is a great resource, especially for my research

Christia 2-3-2014 03:01:19 United States #
Christia

This information is very useful, thanks for the research that you have done.

Jamaal Rafanan 6-3-2014 01:32:14 United States #
Jamaal Rafanan

Find out how to use reputation management for your business for only $30 per month.  Give it a try and see how easy and effective it can be.  <A href="reputation-management.grgprod.com">CLICK HERE</A>

David Jeane 6-3-2014 12:19:34 United States #
David Jeane

See how to use reputation management for your organization for only $30 per month.  Give it a try and see how easy and effective it can be.  <A href="reputation-management.grgprod.com">CLICK HERE</A>

Antonia Coval 6-3-2014 15:22:53 United States #
Antonia Coval

See how the big boys use reputation management.  Spend just $30 a month and become part of the group of successful business owners using this tool.  <A href="reputation-management.grgprod.com">CLICK HERE</A>

Scotty Chaobal 6-3-2014 18:26:33 United States #
Scotty Chaobal

See how to use reputation management for your enterprise for only $30 per month.  Give it a try and see how easy and effective it can be.  <A href="reputation-management.grgprod.com">CLICK HERE</A>

Luanna Sheahan 6-3-2014 19:37:37 United States #
Luanna Sheahan

Hey, how are you?  Ever thought about reputation management and how it can increase your business?  Check it out now.  <A href="reputation-management.grgprod.com">CLICK HERE</A>

whitening toothpaste 8-3-2014 02:11:22 United States #
whitening toothpaste

Nice finding your blog I have gain a lot from it

Lyndon Gagnon 8-3-2014 20:53:23 United States #
Lyndon Gagnon

Hey, how are you?  Ever thought about reputation management and how it can increase your business?  Check it out now.  <A href="reputation-management.grgprod.com">CLICK HERE</A>

chatline 12-3-2014 01:47:19 United States #
chatline

Very interesting info!Perfect just what I was searching for!

Cai Thomas Online Marketing 13-3-2014 20:20:09 United States #
Cai Thomas Online Marketing

With a strong background in IT, ecommerce and online marketing, I consider myself to be an entrepreneurial individual with the potential to seize opportunities and develop successful business propositions from them. Unlike most online marketers or (Geeks) I am unique in the fact that I have an indepth commercial knowledge, meaning that not only am I able to speak technically but translate that in to profitable marketing.

Best Wordpress Plugins 14-3-2014 17:52:24 United States #
Best Wordpress Plugins

Thank you for any other informative site. Where else may just I get that type of information written in such a perfect means? I've a challenge that I am just now operating on, and I have been at the look out for such information.

tootpaste 22-3-2014 17:44:22 United States #
tootpaste

I was searching for something beneficial to read, thanks for sharing

make your dick grow bigger 4-4-2014 08:28:44 United States #
make your dick grow bigger

It�s actually a great and helpful piece of information. I�m glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

Brian 10-4-2014 20:29:24 United States #
Brian

Very nice, thanks for the post.

find out here 18-4-2014 17:43:39 United States #
find out here

I dugg some of you post as I thought  they were  very helpful   very beneficial

Julie Colian 10-6-2015 21:14:20 United States #
Julie Colian

Thanks on your marvelous posting! I certainly enjoyed reading it, you could be a great author.I will be sure to bookmark your blog and may come back in the foreseeable future. I want to encourage you to ultimately continue your great job, have a nice afternoon!

Danny Laverette 12-6-2015 01:51:35 United States #
Danny Laverette

great article for zoho!!

sun 22-6-2015 08:17:10 United States #
sun

Does your site have a contact page? I'm having trouble locating it but, I'd like to send you an e-mail. I've got some recommendations for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it improve over time.

Harland Dolence 1-7-2015 16:07:58 United States #
Harland Dolence

It's the best time to make some plans for the future and it is time to be happy. I've read this post and if I could I wish to suggest you some interesting things or suggestions. Perhaps you can write next articles referring to this article. I want to read more things about it!|

free mp3 download 16-7-2015 14:52:38 United States #
free mp3 download

Free Music MP3 Downloader est un programme qui se charge de télécharger les fichiers MP3

Suggested Web page 22-7-2015 14:22:05 United States #
Suggested Web page

Your site won't show up appropriately on my droid - you might want to try and fix that

Leigha Kniffin 6-8-2015 11:22:38 United States #
Leigha Kniffin

And techies, do not panic. Bing is not getting as much exercise crush Search engine ranking optimization. The one thing that Google is hoping to clarify is you actually cannot do SEO using unfair manner. As per the update made by Google, it says, "If your focus is creating a user interactive, content rich sites that users need to returning and again, make a bookmark or suggest regularly in their friends, then Google Search will align with both you and help you by bringing your site to the top of the the search results". Further it is based clear that now and forever, quality and genuine content become appreciated and valued by Google.

Carrol Hardinger 6-8-2015 11:25:03 United States #
Carrol Hardinger

The first one is your affordability along with the second the your service quality you ripe from solutions. More or less, really are a few many a person need to consider during your search online these SEO vacation packages. Few Steps are here to govern your business making process.

Burt Mcfarland 6-8-2015 11:38:49 United States #
Burt Mcfarland

Brock Paulsen 6-8-2015 14:33:39 United States #
Brock Paulsen

Linking schemes - "I link you so you link to me and the two of us win". Wrongly diagnosed! Now you both decrease. This also includes bought links and too many links on a page. What's more, it includes links in footers to other places of the positioning if the link uses keyword rich anchor text. Links to "bad neighbourhoods" or low quality links. Often you likely have attracted these if you outsourced your SEO to <a href="http://bit.ly/1M6qUP8">Cheap seo</a> companies, used automated link building strategies also automated article distributors.

Ethan Galdo 6-8-2015 14:36:34 United States #
Ethan Galdo

Agua Bendita Acrobacia 6-8-2015 18:33:44 United States #
Agua Bendita Acrobacia

You are my  breathing in, I own  few blogs  and  occasionally  run out from to  brand.