URL Routing for Database Driven URLs in ASP.NET MVC Websites
This Article is for setting up database-driven URL routing for Asp.net MVC website development.
Here we are going to learn, 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 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 URL is used to make a decision for search engines when it is crawling for a particular keyword. This way we can set custom URLs in the 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 the default was handled by only an Asp.net controller/actions.
Don’t worry about that, We have another easy way of controlling the URL routing. here we have our own custom routing and overriding IRouteConstraint interface.
Follow the step-by-step guidelines for setup URL routing in the ASP.NET MVC website. suppose we need a company based on extensionless URLs.
Let’s Start! I have one table with a name like “Companies”.
Here is the ready-made SQL code for the table.
CREATE TABLE [dbo].[Companys]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
NOT NULL,
[SeoFriendlyName] [nvarchar](max) NOT NULL,
[IsActive] [bit] NOT NULL,
NULL,
NULL,
NULL,
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];
Now, create an Asp.Net web application into a solution.
Suppose I want to create a dynamic routing example to my solution with any name. Kindly follow the nine steps below for the solution.
- Add Web Application to your Solution.
- Add Data access in Solution And. Dbml or else .edmx.
- Add your Table in a .dbml or .edmx file.
- Add Interface IRepository.cs in your, DataAccess look like.
namespace Dataccess { public interface IRepository { Company GetComapnyDetailBySeoUrl(string SeoString); Company GetCompanyById(int id); } }
- Implement your Interface method into Repository class add a new file in Data access with the name “Repository.cs”.
namespace DataAccess
{
public class Repository : IRepository
{
// Data context initialization
DataDataContext objContext = new DataDataContext();
// Method to get company details by SEO-friendly URL
public Company GetCompanyDetailBySeoUrl(string SeoString)
{
return objContext.Companies
.Where(o => o.SeoFriendlyName.ToLower().Trim() == SeoString.Trim())
.FirstOrDefault();
}
// Method to get company details by ID
public Company GetCompanyById(int id)
{
return objContext.Companies
.Where(o => o.Id == id)
.FirstOrDefault();
}
}
}
- 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);
}
- Add View Company Index Action (design view as per your requirement).
- 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}");
// Mapping localized route with SEO-friendly URLs
routes.MapLocalizedRoute(
"SeoFriendlyUrl",
"{SeoFriendlyName}",
new { controller = "Company", action = "Index" },
new[] { "DynamicRoutingExample.Controllers" }
);
// Default route mapping
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 SeoFriendlyName = data.Values["SeoFriendlyName"] as string;
// Fetch company details from the database
var objDataRep = new DataAccess.Repository();
var results = objDataRep.GetCompanyDetailBySeoUrl(SeoFriendlyName);
if (results != null && results.Id > 0)
{
data.Values["controller"] = "Company";
data.Values["action"] = "Index";
data.Values["Id"] = results.Id;
}
else
{
// Handle error or redirect to a 404 page
}
}
return data;
}
}
- Open your Global.asax file and RegisterRoutes in Application_Start events like below.
public ActionResult Index(int id)
{
var objDataAccess = new DataAccess.Repository();
var result = objDataAccess.GetCompanyById(id);
return View(result);
}
I hope this above solution will be helpful for you and if you would like any support for a related article you can just comment on a blog.
I have also uploaded the same dynamic URL routing example in the ASP.NET MVC application, You can directly download the example on below Github link below.
https://github.com/prajapatichintan/database-driven-urls-for-asp-net-mvc-website
You may also like my other interesting articles for ASP.NET MVC.
Further Reading: How to Enable Theme Customization Dynamically in ASP.NET MVC?