Subscribe to Youtube channel

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

Root your Gingerbread 2.3.4 android Mobile Phone

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

Disable backspace key using Jquery

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

Implement Nlog in .Net core MVC application part 1

Devexpress Datebox date formatting in angular 6 with example

Angular User Session Timeout example step by step

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

Add Comma automatically while entering amounts in textbox using Javascript