Asp.Net MVC best practices part 1

If you decided to develop the application using Asp.Net MVC application and. I am going to demonstrate you to follow the best practices in MVC to develop the robust web application. If you want to log the exceptions occurs in controllers you need to write try catch blocks in each action method. This approach is also not recommended because you need to write try catch block in each action method. To get ride of this you can handle exceptions and log each exception by using centralized approach. These approaches are as follows

  • Do not inherit the Controller base class directly to your Controllers
  • Create new base custom controller class which inherits the base controller class
  • Inherit created base custom controller class to your controllers
Following is the sample code which demonstrate the above best practices


  public class BaseController : Controller
  {


  }

In above code I have inherited the controller class to custom base controller class and below is the code to use this created custom base controller class to my controllers.


 public class HomeController : BaseController
 {
        public ActionResult Index()
        {

            Appcontext db = new Appcontext();
            var BranchList = db.Branches.ToList();



            return RedirectToAction("About");
        }

 }

by above code sample we can do lots of centralized stuff wich can be managed by single custom base controller class.

I have used above code to handle exception and log each exceptions in single centralized custom base controller class. Following is the code snippet to achieve that.



 public class BaseController : Controller
 {

        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            String ExceptionLog = filterContext.Exception.Message;
            String InnerExceptionLog = filterContext.Exception.InnerException.Message;

            filterContext.ExceptionHandled = true;
            

        }

        
 }

By overriding OnException method all the exceptions occured in the application invokes the OnException method of controller class.

This is how we can centralize the things in Asp.net MVC to manage the large scale applications using minimal efforts. 



  

Comments

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Restore the lost focus of Auto post back controls in asp.net update Panel control

Disable backspace key using Jquery