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)

            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 MVC to manage the large scale applications using minimal efforts. 



Popular posts from this blog

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

Clone a generic list in C# using extension method

Disable backspace key using Jquery

Add Comma automatically while entering amounts in textbox using Javascript

Step by step migration of ASP.NET Core 2.2 to 3.1

Source Code Beautifier And Format Source Code For Blogger and Websites

Remove Owin from MVC 5 Application and use custom forms authentication

How to Import CSV File and bind csv file data to gridview in using c#

Email validation using regular expression in jQuery