Few ways of Handling Exceptions in ASP.NET MVC

Exception handling is one of the major areas of an application development and when it is a web application, it requires additional care so that errors gets handled gracefully without breaking the complete system and relevant information is shown to the users with proper error message. Also making sure that no internal details gets propagated till user when application crashes or error occur because it could be a major security threat. All the exception details and other additional information should be logged so that it can be later used for proper investigation. In this post we will talk about the few options available to handle the exception in ASP.NET MVC and best practices to use them.

In ASP.NET MVC, the request first hits the route handler which identifies the controller and action to be serving the request. We put the whole logic in our controller itself. There are various type of filters in ASP.NET MVC that are also part of the request processing and some time we extend them to put some custom logic based on specific requirement. There is an Exception filter for handling exceptions as well and this Filter is key in handling exceptions in MVC. First let’s see available filters and their order of execution in request processing flow


So we can see here that there are four filters in total and exception filter executes at end. It means if we use exception filter then it will be caught there whether the exception occurs in Action or even in Authorization/Action/Result filters.

Note – Filters are added as an attribute so it also inherits from ‘System.Attribute’.

Broadly we can say that exceptions may occur in controller or in some cases while processing the routes and filters. But as most of our core logic resides in action so the chances in are most. Before focusing on filters, let’s first discuss one basic way to handle to exception that is part of C#.

Using Try/Catch block

This is C# feature and one of the basic ways to handle exceptions so we can wrap all our code in our Action as below.

    // Add your code here
    // Exception Handling code

But there are many issues with this approach and the primary issue is the limitation to single Action. To handle that, we need to put try catch block in each Action of the application which is repeating the same exception handling code which defies the code re-usability logic. It does not mean that we should never use it but there are some scenarios where we require to perform some another activity in case of exception without letting the user know or more specifically if you are calling to some third part services etc. then it might be a good Idea to use this approach.

Global Error Handling

Global error handling is one of the simplest way to handle exceptions at application level. It leverages the Exception Filter to handle exception and applies at application level itself. This is out of the box feature and can be easily set up by following step.

  1. Set customErrors errors as On in web.config as
    <customErrors mode="On"></customErrors>
  2. Have a common error view (in Shared folder with name error.cshtml) which will be shown in case of error aserrorviewHere we see that we get a model of type HandleErrorInfo class which provides the details about that error occurred, controller and action name etc.
  3. Make sure we registere HandleErrorAttribute in Application_Start (Global.asax)method
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
         filters.Add(new HandleErrorAttribute());

    Now if any error occurs then error view will be shown.

Customizing global error handling

We have seen that how easily we can configure the error handling at application level. But what if we want to handle it bit differently. Say we want to save the details in database and/or want to send the email notification when error occurs. We have two options here

  1. Override OnException method :

    We can override OnException method as in our controller as

    protected override void OnException(ExceptionContext filterContext)
        Exception ex = filterContext.Exception;
        // Log Exception ex in database
        // Notify  admin team
        filterContext.ExceptionHandled = true;
        // Setting the View in case of error
        filterContext.Result = new ViewResult()
            ViewName = "CustomErrorView"

    Here we can log our exception, send the mail etc. and set our own view that will be shown (like here I used CustomErrorView) in case of error. But this code won’t be reusable and need to write in each controller wherever we need.

  2. To handle it in better way, we need to extend HandleErrorAttribute as
    public class MyCustomHandleErrorAttribute : HandleErrorAttribute
        public override void OnException(ExceptionContext filterContext)
                       Exception ex = filterContext.Exception;
                	     // Log Exception ex in database
                	     // Notify  admin team
                	     filterContext.ExceptionHandled = true;
            filterContext.ExceptionHandled = true;
            filterContext.Result = new ViewResult()
                ViewName = "DVZ"

    And instead of registering the default HandleErrorAttribute we need to register the custom one as

    filters.Add(new MyCustomHandleErrorAttribute());

    Now this custom error attribute will be used in the whole application.

Handling exception at more Granular level

Till now, we have seen that how can we apply filter at global level. MVC allows us to handle exceptions at more granular level similar at controller and action level as

For Controller either we can use the default HandleErrorAttribute or we can use the extended attribute similar to MyCustomHandleErrorAttribute and put it at controller as

public class EventController : Controller
// Controller code

For Action

public class EventController : Controller
public ActionResult About()
	// Action code

Note – Here I have put ‘MyCustomHandleError’ as an attribute. We can use default ‘HandleError’ attribute instead of custom one.

Another variation

There may be some scenarios where we may need to show specific view or details based on the type of exception occurs in Controller/Action. In other words, say if in Controller/Action, if a specific exception occurs, then showing user one view and any other exception occurs then show a different view. Let’s see an example

[HandleError(ExceptionType = typeof(DivideByZeroException), View = "DVZ")]
public ActionResult Create()
	// Action code

Here if DivideByZeroException occurs then view DVZ will be loaded else default one would be loaded. We can add as many type of exception based on requirement. Also similarly we can apply at Controller level as well.

ExceptionHandled property usage

In OnException method, you must have seen the following line many times.

filterContext.ExceptionHandled = true;

As the name suggests that when we set it true (default: false), then the exception does not propagate further and it is handled in the same method. Say we have put the Exception Filter at action, added a Global exception filer and we did not set the ExceptionHandled filter or set it false then once the exception is caught by action level exception filter that will be thrown further to next level and caught at global filter. Normally when we handle exception we make it false because we have already handled the exception. But there could be few scenarios where we do something with exception details and throw it further so accordingly we need to set this property.

Exception handling outside the scope of MVC

Exceptions are bound to happen and it can always find the way to reach user. We need to block every route. As we know handled the exceptions using MVC framework features but if something happens outside of the MVC scope. As we know that MVC framework is built on top of the ASP.NET platform then we can use the Application_Error method that is available since beginning to handle Application level error. It can be depicted pictorially as

Here we can see that once the control reaches ASP.NET platform, this method can help us so we should handle the exception here as well and we can put all the logging and notification code here as

protected void Application_Error()
    Exception ex = Server.GetLastError();
    // Log Exception ex in database

    // Notify  admin team

    // Clear the error

    // Redirect to a landing page

Note: Application_Error should not be used in replacement MVC global exception filer, because as soon as you get out of MVC scope, you won’t get its execution context which is very important to provide the relevant details about the exception.


We have discussed various possible ways of handling exceptions. We find that all the exception handling moves around the handle error attribute with many variations. Another two that we discussed: using try catch block and using Application_Error. Best solution for any application would be a combination of these approaches like extend HandleErrorAttribute based on the requirement and use it accordingly. Application Error should be used as if an exception somehow find its way to get out from MVC scope, then it will be caught here. Try Catch block should be really avoided as it just not makes the code ugly but we can miss lots of relevant information that may be helpful in fixing the issue so unless specific case, do not use it.


Learning ASP.NET Web API [Packt] – ASP.NET Core RC1 to ASP.NET Core 1.0

Hello All,

Recently, I published a video course on ASP.NET Web API using ASP.NET Core framework. Initially, when I started working on it, it was named as ASP.NET 5 and as it progressed till last section, Microsoft announced to rename it as ASP.NET Core and RC2 got released few days prior to the course release date. Microsoft took more than six months to release the next RC version. Although the concept was same but there were major changes in tooling and libraries. As it was not the final version so we decided to provide the details of differences once RTM releases.

In this post, I will be putting the details of the changes by section and also update the sample which will be available with the course. As ASP.NET 5 got renamed to ASP.NET Core, accordingly the names of libraries got changed to ASP.NET Core as well so we need to change all the references. The following table contains the details of packages that we need to update in our sample with the video number.

ASP.NET 5 Reference (Earlier) ASP.NET Core 1.0 Reference (Current) Video#
Microsoft.AspNet.Mvc Microsoft.ASPNETCore.MVC 2.2
Microsoft.AspNet.Mvc.Formatters.Xml Microsoft.AspNetCore.Mvc.Formatters.Xml 2.4

Updated sample is available with the course and refer the project.json to find the updated references. Also, Microsoft again reintroduced web.config file but it will be there along with Project.json.

Note – The details will be included for only for those those sections where changes are required.

Section 2   
As this was the first section where we started our discussion on ASP.NET Core Web API and started working on our sample so this section got many changes. Let’s discuss each

Video 2.1 : There are changes in the project creation flow. Earlier when we used to create ASP.NET Core project, it used to have two sets of references – one for core and other for full framework. We either used to build the application using both the framework and remove one based on our needs. As there were many libraries which could not work in both the platforms so Microsoft has provided the option to select the framework upfront while creating the project which makes the complete process simpler. Also, in real world scenarios, there are rare chances when we need to build the binaries for both the framework.  Now when we open New Project window and select web from left side then we get three options as
2.1Here we have three options.

  1. First one is a traditional ASP.NET application using .NET 4.6.
  2. Selected one is ASP.NET Core application using .NET Core framework and the same is used in our course.
  3. Third one is again ASP.NET Core application but uses the standard .NET framework.

When we select the second option, it shows the following dialog


It also got revamped completely. We had earlier lots of options which included standard ASP.NET templates. Now it contains only ASP.NET Core templates and has three options same as earlier ASP.NET 5 templates and we used the empty template for our course. Just to mention again, now we have just one bag named as .NETCoreApp,Version=v1.0  which contains set of libraries for .NET Core only in the references.

There are some more changes as below

a) Earlier we used to have following line in startup.cs which was entry point for the web application

// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);

but now we have a new file program.cs which contains the main method which is now entry point for the web application.

b) Configuration file web.config is also back in project file and available along with project.json although all the settings should be put in project.json and we will be using the same.

c) There are also changes in the number of the parameters in ConfigureServices method in startup.cs which includes Hosting Environment and logger factory but we will not be using it in our sample.

Video 2.2: Only change in the references. Refer the initial table.

Video 2.3: In this video, we discussed that there are four options to register a service but we found AddSingleton and AddInstance very similar, both allows single instance across multiple requests with a difference in the instance creation. Now we have only AddSingleton where either we can pass the instance or provide the type info as.

To register via interface and class name

services.AddSingleton<IBookStoreRepository, BookStoreRepository>();

and to register an instance

IBookStoreRepository bookStoreRepository = new BookStoreRepository(new BookStoreContext());

Video 2.4: Only change in the references. Refer the table.

Section 3
In this section we added CRUD operations to our sample using  HTTP verbs. Only few changes are required in the section as mentioned below.

Video 3.2: Microsoft did an awesome change with it by making the JSON response in camel case by default. In our sample we added serialize settings in statrtup.cs as

options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

It is no more required.

Video 3.3 :  We returned various status codes from the action methods based on the request.The classes that we used also got renamed as

ASP.NET 5 ASP.NET Core 1.0
HttpUnauthorized Unauthorized
HttpNotFound (and its overloads) NotFound
HttpBadRequest (and its overloads) BadRequest

The above changes has taken place in all the action methods wherever used.

Section 4 
In this section, we added few more features to our sample like sorting, paging etc. Here there is a change in the way we access URL Helper as discussed below.

Video 4.3: We used URL helper for generating the URLs and it was injected via constructor without any other changes as it was by default available which is not the case now.

Now we need to access it via UrlHelperFactory and action context. ActionContext is accessed via ActionContextAccessor, for that we need to register it in startup.cs as

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

and we need to inject the UrlHelperFactory and ActionContextAccessor in constructor to get the URL helper as

  public BooksController(IBookStoreRepository _repository, IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionContextAccessor)
            this.repository = _repository;
            this.urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);

Rest of the code would be same as we got the similar URL helper.

Section 5
In this section we talked about security implementation. In it we have only few changes as below.

Video 5.2 : We created a custom authorization attribute RequireHttpsAttribute which inherited from AuthorizationFilterAttribute where we checked the scheme from the URL. Now RequireHttpsAttribute is itself available under the namespace Microsoft.AspNetCore.Mvc so we can use the same to enforce the SSL in complete application or any specific controller/action.

Video 5.4 : Only few references changes. Refer the table

Section 6 
In this section, we discussed some advanced topics like DI, CORS etc and there are few changes in DI. Let’s see that

Video 6.1:
a) As discussed earlier that now we don’t have AddInstance option for registering the service, same can be achieved via AddSingleton.

b) We discussed that we can also inject services via property using FromServices attribute but it is not available any more as it was creating confusion and issues. Constructor injection is always preferable. From services is available and can be used for Action Injection as

public IEnumerable<Book> Get([FromServices] IBookStoreRepository repository)

These are the key changes that took place specific to Web API and our course. I created again the sample from scratch using the ASP.NET Core 1.0 which can be downloaded from the course.

Thanks a lot for your support and feedback.


My Video Course : Learning ASP.NET Web API

Hello All,

9781785885945I am very happy to announce that my video course  Learning ASP.NET Web API using ASP.NET Core 1.0 got published. This course is for all the ASP.NET Developers who have little or no experience to Web API as it starts from basics and covers all the key aspects of Rest-ful services with real world examples. It will be similarly helpful to experienced Web API devs because developing it using ASP.NET Core is completely different and many old concepts cannot be used as it is.

The vision of the course is that the viewers understand that how to develop a RESTful web API using the ASP.NET Web API service, and be able to implement a service with a range of data transfer and handling operations. They will understand RESTful service architectures and how different types of application data can be exposed with a web API, to different client endpoints.Let me give overview of the course.

The key features of the course are

  • Develop a complete enterprise level REST based HTTP services from scratch using ASP.NET Core Web API with latest standards.
  • An example driven course from starting from basics of REST with brief description of new ASP.NET framework ASP.NET Core.
  •  Discusses all the building blocks: Routing, Controllers, Content Negotiations and security with advance topics like versioning, dependency Injection, caching etc.
  • Includes the tips and best practices for making robust and scalable APIs.
  • Full of pictorial presentations for core concepts, practical examples and clear step by step instructions with tips and best practices.

What you will learn from this course.

  • Understand REST basics and its constraints with real life examples.
  • ASP.NET Core framework changes and its impact of ASP.NET Web API.
  • Building blocks of ASP.NET Web API : Routing Controllers, HTTP verbs with scenario bases example.
  • Implement various data transfer operation and Content negotiation.
  • Various security implementations options including OAuth, CORS.
  • A good hand holding of Advance topics like dependency Injection, API versioning, HTTP Caching etc.
  • Consuming Web API end points using a real world client.
  • Tips and best practices of writing better, highly scalable and performant Web API service.

To find more about the video course and watch the sample video Click here.

Thanks a lot to all of you for your continuous support and feedback. Thanks a lot to Packt publishing for providing me the opportunity for this course and being supportive throughout the journey. Thanks a lot to my friends specially Arun for his time, support, feedback and reviews. Also I cannot forget to thanks my wife Renu for being so supportive and taking care of my son Anvit during my late night hours and weekends. Without their support it would not have been possible.

This book is based on my personal learning via blogs, samples, white papers, projects, POCs and many other sources. It has no relations with any of my current and previous employers. As this course is built on ASP.NET Core 1.0 which is not yet completely out and you may expect some changes in the final version. If you find any mistakes or have some constructive feedback, you can share it with me on my mail id – brij.mishra@outlook.com  I will try my best to address that at earliest.

Again, thanks a lot to all of you for your support and feedback. I am sure you will find it useful and will be very happy to see your valuable feedback and comments.


SQL Server In-Memory OLTP as ASP.NET Session State Provider

Internet applications use the HTTP protocol, following a request-response paradigm. As each request is independent of the other, we need to find a way to maintain some information across multiple requests. For that, either we put all the common data in each request, or we put key(s) in request(s) to store the data on the server against each key.

State management is a basic requirement for any web application. As a user interacts with an application, we need to maintain the user’s preferences — the application state with its corresponding actions…Read complete post on sitepoint.com

Building Real time application with SignalR – Part 1

HTTP protocol is the basis for all communication over the web, and it has catered to our needs since the early days. HTTP works in a request and response model, where a request needs to be sent to the server to get any update from there. This creates challenges in handling a few scenarios where we need real time data: when a user opens a web page then it needs to be updated, and when there is a change on the server but as per the HTTP architecture, a new request must be sent to get an update from the server. This creates a bad experience for the user and multiple requests may throttle…Read complete post on Infragistics blog.


Presented on REST and ASP.NET Web API in C# Corner South India Meet : 31st Jan 16

Hello All,

On 31st Jan 2016, C# corner organized a major event named as South India Meet in Hyderabad. This event got an awesome response from the developer community where more than 500 people registered for the event and was attended by 200+ developers. A series of hot topics were discussed including REST, ASP.NET Web API. AngularJS, Phonegap etc which was very much appreciated by the audience. I presented on Building Rest Services using ASP.NET Web API and audience enjoyed the talk with full of enthusiasm and energy in spite of the last session of the day.  For the popular demand, I am attaching the slides and sample at the end of this Post. Some snaps of the event



CaBySP-UEAAlbY7We also announced the North India’s largest conference C# Corner Annual Conference which will be taking place in Noida during 18-19 April 2016.

For complete details of C# Corner Conference Click here.

Sample code

Please note that the solution was built using Visual Studio 2015 Update1 and ASP.NET RC1. You can download the community edition of Visual Studio to get going and exploring more features.

Thanks a lot to all attendees and hope you all have enjoyed the day.

Do share you feedback and let us know if you want to hear any specific topic

You may like to download AngularJS book from here



Leveraging the Power of Asynchrony in ASP.NET

Asynchronous programming has had a lot of attention in the last couple of years and there are two key reasons for this: First it helps in providing a better user experience by not blocking the UI thread which avoids the hanging of the UI screen until the processing is done and second, it helps in scaling up the system drastically without adding any extra hardware.

But writing asynchronous code and managing the thread gracefully was a tedious task. But as the benefits are tremendous.. Read complete post on Infragistics blog

12 tips to increase the performance of ASP.NET application drastically – Part 1

Building web application and hosting it on a web server is insanely easy with ASP.NET and IIS. But there are lots of opportunities and hidden configurations which can be tweaked that can make it high performance web application. In this series post, we are going to discuss some of the most unused or ignored tricks which can be easily applied to any web application.

  1. Kernel mode cache – It is one of the primary tools widely used for writing making web application faster. But most of the times, we don’t use it optimally and just leave some major benefits. As each asp.net request goes through various stages, we can implement caching at various level as belowcachingoppWe can see that request is first received by http.sys so if it is cached at kernel level, then we can save most of the time spent on server as http.sys is a http listener which sits in OS kernel…Read complete post on Infragistics blog

OutputCache doesn’t work with Web API – Why? A solution

Output Cache is one of the most useful features of ASP.NET and plays a key role for making high performance web applications. It’s very easy to use this feature. Just put OutputCache attribute on any controller/action or you can set outputCacheSettings attribute in web.config. ASP.NET MVC and ASP.NET Web API are two technologies that looks very similar when we work with them. They have similar concepts like Controller, Action, routing etc and work almost in similar way except one returns View and returns data in JSON/XML format.

Recently in an application, I was required to cache some web api calls so I put the OutputCache attribute over the Web API action but when I ran it was not working. The data was not getting cached and on every request, it was going to server and further fetching data from database and returning the same. Then to verify the attribute, I put the same attribute over a MVC action and it was working like a charm. So I felt that it looks like that this attribute is not working. Continue reading

IIS7 and Higher : system.webServer element ApplicationHost.config vs Web.config

Hi All,

This is another post on Authentication for ASP.NET applications. In one of my last posts, I talked about setting up authentication mode as Windows in web.config and Enabling/Disabling windows authentication at IIS. You can access that post from the below link.

Looking into Windows authentication at Web.config and at IIS
Continue reading