ASP.NET Slug (MVC)

I want to use slug in ASP.NET MVC application. The URL should be something like this

localhost:58128/ABMB 

Here are the steps required to do so:

1. Defined the route (startup.cs)


 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 routes.MapRoute(
   "Slug",
   "{slug}", 
       new { controller = "Home", action = "ScholarInfoDetails" } 
 );

2. Create SlugToIdAttribute.cs class

using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

/// 
/// Summary description for SlugToIdAttribute
/// 
public class SlugToIdAttribute : ActionFilterAttribute
{
    private ApplicationDbContext db = new ApplicationDbContext();

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var slug = filterContext.RouteData.Values["slug"] as string;
        if (slug != null)
        {
            var model=db.Banks.Where(x => x.Code == slug).First();
            if (model != null) {
                filterContext.ActionParameters["id"] = model.id.ToString();
            }            
        }
        base.OnActionExecuting(filterContext);
    }
}

3. Use in the controller. Add annotation [SlugToId]  

[AllowAnonymous]
[SlugToId]
public ActionResult ScholarInfoDetails(String id)
{
	var r = new ContentResult();
	r.Content = "Hello World " + id.ToString();
	return r;
}


Now the function can be access using slug. E.g http://localhost:58128/ABMB. Result will be something like this :
Hello World 2

0 comments:

 
Copyright © peyotest