Creating Custom Controller

To create the custom controller factory you need to implement IControllerFactory Interface and register the class in global.asax. Bellow mention code explains how we can load a controller on the basis of browser language selection .

Example  

 customeControllerFactory.cs  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.EnterpriseServices;
namespace MyViewEngine.CustomControllerFactory
{
public class customeControllerFactory : IControllerFactory
{
public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
if (string.IsNullOrEmpty(controllerName))
throw new ArgumentNullException("controllerName");
string language = requestContext.HttpContext.Request.Headers["Accept-Language"];
string controllerType = string.Empty;
if (language == "fa-IR")
controllerType = string.Format(ConfigurationManager.AppSettings["FarsiControllerTypePattern"], controllerName+"Controller");
else
controllerType = string.Format(ConfigurationManager.AppSettings["EnglishControllerTypePattern"], controllerName + "Controller");
var t = Type.GetType(controllerType);
IController controller = Activator.CreateInstance(Type.GetType(controllerType)) as IController;
return controller;
}
public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
{
return System.Web.SessionState.SessionStateBehavior.Default;
}
public void ReleaseController(IController controller)
{
if (controller is IDisposable)
(controller as IDisposable).Dispose();
else
controller = null;
}
}
}
--------------------------------------------------------------------------------------------------------------
In Global.asax register on application start the code mark in red
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(typeof(customeControllerFactory));
}
--------------------------------------------------------------------------------------------------------------
In application level web.config you need to add the following code




Published by Nirbhay

Technology Geek,Blogger,Reviewer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: