URL Routing for Database Driven URLs in Asp.Net MVC Website

Introduction

This Article is for the setting up database driven URL routing for ASP.Net MVC website development. Here we are going to learn that, how to customize the ASP.NET MVC website by URL routing and route variable URL paths to a controller and action of our choice. Mainly the URL routing is most important for making SEO friendly ASP.Net MVC websites.

Why We Need Custom URL Routing in ASP.Net MVC

Nowadays in technology, everybody wants to access the site as www.youdomain.com/a1, www.yourdomain.com/a2, etc. with a1, a2. mainly this type of URLs is useful to make a decision for search engines when it is crawling for a particular keyword. this way we can set custom URLs in ASP.Net MVC website. so that we can make a successful SEO Friendly website by making a little c# code in ASP.Net MVC.

Let’s discuss and set up how to make custom URL routing for making SEO friendly ASP.Net MVC website.

Url routing with ASP.Net MVC, I had a problem because default URL routing is handled by only asp.net controller/actions.

Don’t worry about that, We have another easy way for controlling the URL routing. here is we have own custom routing and overriding  IRouteConstraint interface.

Follow the step by step guideline for setup URL routing in ASP.Net MVC website. suppose we need company based on extension less URLs.

Hire Now!

Do You Need Help From Dedicated ASP.Net MVC Developer?

Hire our best ASP Net MVC developer on hourly, Full-time, Part-time bases. We are ready to help you resolve the problems for ASP Net MVC web development.
Hire Now!

Step 1: I have one table with name like “Companies”

SeoFriendlyTable

Here is ready-made SQL code for the table.


CREATE TABLE [dbo].[Companys](

[Id] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [nvarchar](50) NOT NULL,
[SeoFriendlyName] [nvarchar](max) NOT NULL,
[IsActive] [bit] NOT NULL,
[City] [varchar](50) NULL,
[State] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[Photo] [varchar](50) NULL,
[StartDate] [datetime] NULL,
[Employees] [int] NULL,
[Decription] [nvarchar](max) NULL,
CONSTRAINT [PK_SeoFriendlyRoute] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Step 2: Now, just create an Asp.Net web application into solution.

Suppose, I would like to create a dynamic routing example to my solution with any name. kindly follow below nine steps for the solution.

  1. Add Web Application in your Solution
  2. Add Data access in Solution And .Dbml or else .edmx.
  3. Add your Table in .dbml or .edmx file
  4. Add Interface IRepository.cs  in your, Dataccess look like
namespace Dataccess
{
public interface IRepository
{
Company GetComapnyDetailBySeoUrl(string SeoString);
Company GetCompanyById(int id);
}
}

5. Implement your Interface method into Repository class add a new file in Data access with name “Repository.cs”

namespace DataAccess
{
public class Repository : IRepository
{
DataDataContext objContext = new DataDataContext();
public Company GetComapnyDetailBySeoUrl(string SeoString)
{
return objContext.Companies.Where(o => o.SeoFriendlyName.ToLower().Trim() == SeoString.Trim()).FirstOrDefault();
}
public Company GetCompanyById(int id)
{
return objContext.Companies.Where(o => o.Id == id).FirstOrDefault();
}
}
}

6. Add Company Controller in your MVC web application Project and Index Action like.

public ActionResult Index(int Id)
{
var objDataAccess = new DataAccess.Repository();
var Result = objDataAccess.GetCompanyById(Id);
return View(Result);
}

7. Add View Company  Index Action (design view as per your requirement).

8. Open your Routeconfig.cs file in your web application project and modify RouteConfig.cs file like below

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapLocalizedRoute("SeoFriendlyUrl",
"{SeoFriendlyName}",
new { controller = "Company", action = "Index" },
new[] { "DynamicRoutingExample.Controllers" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

}

public static class LocalizedRouteExtensionMethod

{
public static Route MapLocalizedRoute(this RouteCollection routes, string name, string url, object defaults, string[] namespaces)
{
return MapLocalizedRoute(routes, name, url, defaults, null /* constraints */, namespaces);
}
public static Route MapLocalizedRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
{
if (routes == null)
{
throw new ArgumentNullException("routes");
}
if (url == null)
{
throw new ArgumentNullException("url");
}

var route = new clsRouteData(url, new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints),
DataTokens = new RouteValueDictionary()
};

if ((namespaces != null) && (namespaces.Length > 0))
{
route.DataTokens["Namespaces"] = namespaces;
}

routes.Add(name, route);

return route;
}
}
public class clsRouteData : Route
{
public clsRouteData(string url, IRouteHandler routeHandler)
: base(url, routeHandler)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData data = base.GetRouteData(httpContext);
if (data != null)
{
var SeoFriendliyName = data.Values["SeoFriendlyName"] as string;
//get here from Database;
var ObjDataRep=new DataAccess.Repository();
var Resutls = ObjDataRep.GetComapnyDetailBySeoUrl(SeoFriendliyName);
if (Resutls != null && Resutls.Id>0)
{
data.Values["controller"] = "Company";
data.Values["action"] = "Index";
data.Values["Id"] = Resutls.Id;
}
else
{
// Add Error page here.
}
}
return data;
}

}
}

9. open your Global.asax file and RegisterRoutes in  Application_Start events like below.

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}

I hope this above solution will be helpful for you and if you would like any support for a related article you can just a comment on a blog.

I have also uploaded the same dynamic URL routing example in asp.net MVC application, You can directly download the URL routing example on below Github link.

https://github.com/prajapatichintan/database-driven-urls-for-asp-net-mvc-website

You may also like my other interesting solutions in Asp.Net MVC.

By | 2017-09-20T11:15:07+00:00 April 4th, 2015|Asp.Net, Asp.Net MVC, SEO Friendly|