Friday, May 4, 2012

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  
 <appSettings>  
     <add key="EnglishControllerTypePattern" value="MyViewEngine.Controllers.En.{0}, CustomViewEngine"/>  
   <add key="FarsiControllerTypePattern" value="MyViewEngine.Controllers.Fa.{0}"/>  
  </appSettings>  

No comments:

Post a Comment