0

I know attribute based routing works on action level but can I use same at controller level for following scenario?

I have a controller with name C1Controller but I want when url contains C1 or C2 or C3 then C1Controller to invoke. How to use Route attribute to achieve this?

Imad
  • 7,126
  • 12
  • 55
  • 112
  • Can you give an example url that contains the `C1` or `C2` that would map to `C1Controller`. This is so that a proper route template can be suggested to satisfy your requirement. – Nkosi May 24 '16 at 09:25

2 Answers2

0

Got answer from a post

"The most correct way would be to create a class that inherits ActionFilterAttribute and override OnActionExecuting method. This can then be registered in the GlobalFilters in Global.asax.cs"

Like:

public class InspectActionFilter : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       //Check URL for c1, c2 ... and redirect if found
   }
}

To use it, just add it to the global filters in global.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new LogActionFilter());
}

Ref: Intercept all calls

ASP.NET MVC 4 intercept all incoming requests

Hope this helps!

Community
  • 1
  • 1
Sami
  • 3,686
  • 4
  • 17
  • 28
0

Try This one

public class TheActionFilter: ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        if (controllerName !="C1" || controllerName !="C1" || controllerName !="C3")
             return;
        var redirectTarget = new RouteValueDictionary
           {{"action", "ActionName"}, {"controller", "ControllerName"}};
        filterContext.Result = new RedirectToRouteResult(redirectTarget);      
        filterContext = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsolutePath)              // The session you can get from the context like that:
        var session = filterContext.HttpContext.Session;
    }
}

In Your Controller

[TheActionFilter]
public class BookController : Controller
{
    // Your Action Results
}
Dinesh J
  • 113
  • 11