You are on page 1of 77

In the growing realm of web applications, various frameworks have been introduced, and one of them is

ASP.NET MVC.
ASP.NET MVC 5 (version of ASP.NET MVC) is an open-source web app program having a compiled
architecture of MVC (Model-View-Controller). It was released by Microsoft specifically to build flawless
and up-to-date functions in the application. Due to the framework, the process of building ASP.NET MVC
web applications becomes speedier and more convenient for several ASP Dot Net services.
Due to its compatibility with HTML and JavaScript codes, the framework can be combined with other
frameworks like ASP.NET MVC 5 Angularjs.
While reading further, you will learn about what is ASP.NET MVC 5, its benefits, and how to build an
ASP.NET MVC application.
Overview of ASP.NET MVC
Image Source: codeproject.com
ASP.NET MVC (Model-View-Controller) is a web development framework by Microsoft for building
dynamic web applications. It is supported widely by the HTML, JavaScript, CSS, and C# libraries for code
reusability and web app scalability.
For distinct functionality, the MVC model separates an application into three key components:

Model
This represents the data and business logic of the application. It manages data, rules, and algorithms,
ensuring the application’s core functionality.
View
The view is responsible for displaying the user interface. It presents data from the model to the user and
captures user interactions. It focuses on the visual representation and user experience.
Controller
Controllers handle user input and orchestrate the flow of data between the model and the view. They process
incoming requests, trigger actions in the model, and update the view accordingly.
ASP.NET MVC application is simplified from this separated model – Data (model), User interface (view),
and application logic (controller). Combining all these components increases the responsiveness and
functionality of the application.
To this extent, it enables the developers to work on every single component of the application
independently. It promotes code quality and maintenance. It also supports various features like routing, URL
mapping, and data validation. The framework is widely used for building modern, interactive web
applications with an organized architecture.
Benefits of ASP.NET MVC Application
Distribution of tasks
Each component of MVC has separate functions. Model (M) for data management, View (V) for user
interface, and Control (C) for app logic execution. This makes it easier for the developer to work in units and
not combined.

Interactive User Interface


The data is segregated and managed within the model component. Since only the relevant content needs to
be displayed on the front page, the view allows selective data to be showcased on the user page. In this way,
the ASP Dot Net services manage the data and feature representation.
Back Support for Testing
Web forms are an event-driven model for creating web applications. The developers use it in compilation
with MVC architecture for editing, modifying, and developing the codes. It helps with code testing and
application functionality.
Large Ecosystem
ASP.NET MVC 5 contains robust libraries of HTML, CSS, JavaScript, and C#. Because it includes the
major languages, it generally requires developers of the same domain to handle and modify the code. Hence,
it has an extensive ecosystem and resources to create and edit the ASP.NET MVC application project.
Life Cycle of ASP.NET MVC 5
In this section, we will showcase the overall MVC structure and the process of HTTP requests within the
framework in ASP.NET MVC 5.
There are two life cycles:
 Application life cycle
 Request life cycle
Application Life Cycle
VImage Source: tutorialspoint.com
The cycle refers to the time when the application process initially starts running IIS till the time stops. It
marks the start and end events in the startup file.
Request Life cycle

Image Source: tutorialspoint.com


It is an entire cycle of events that occurs while handling the HTTP request of the application.
It starts with the entry point from the routing. As the ASP.NET MVC application receives a request, it sorts
the way to handle the request through the URL routing module. This routing module is responsible for
matching the incoming URL to routes. Then, the MVC architecture handles the conversion of route data into
a controller that handles the requests.
Next, the major step is Action execution. The component action invoker finds and selects an appropriate
action method to call up the controller.
Web Application Security Best Practices
After the result is prepared, the next stage is result execution. The MVC model separates result declaration
from executing the result. If the result is view type, the view engine will be called to find and render the
view. But if it is not, the action result will self-execute. This generates an actual response to the HTTP
request.
Steps for Building ASP.NET MVC Web Applications
The below-mentioned steps are a guideline for creating a web application project flawlessly.
Step 1: Open the Visual Studio. Click File → New → Project Menu Options
Image Source: tutorialspoint.com
Here, a new project dialog will open.
Step 2: From the left slab, choose Templates → Visual C# → Web
Step 3: From the middle slab, select ASP.NET MVC Web Application
Step 4: Name the project ‘MVCFirstApp’ in the name box. Then click OK to continue. After that, a dialog
box will appear that will ask you to set the initial content for the ASP.NET project.
Image Source: tutorialspoint.com
Step 5: Select the ‘Empty’ option. Check the MVC checkbox in the Add folders and also in the core
references section. Click Ok.
From then, it will create a basic MVC project with nominal predefined content. As the project gets created in
Visual Studio, you will see several files and folders displayed in the Solution Explorer Window.
Image Source: tutorialspoint.com
As you have created the ASP.NET empty project template, the application would not contain anything to run
the application. So,
Step 6: Run the application from Debug → start debugging menu option and you will get the message of
404 not found error.
Image Source: tutorialspoint.com
Although the default browser will be Internet Explorer, you can select any installed browser from the
toolbar.
Steps for Adding a Controller
It is vital to remove the 404 not found error. For that, we need to add a controller that will handle all the
incoming requests.
Step 1: To add a controller, make a right click on the controller folder in the solution explorer. Add →
Controller
Image Source: tutorialspoint.com
Then, it will showcase the Add Scaffold dialog.
Image Source: tutorialspoint.com
Step 2: Select the MVC controller. Choose the empty option and click the ‘Add’ button.
The Add Control dialog will appear.

Image Source: tutorialspoint.com


Step 3: Set the name ‘Home Controller’ then click the Add button.
A new C# file in the HomeControler.js will appear in the Controllers folder. This is open for editing in the
Visual Studio also.
Image Source: tutorialspoint.com
Step 4: Run this application and you will see the browser displaying the result of the Index action method.

Image Source: tutorialspoint.com


ASP.NET MVC Life Cycle
 Read

 Discuss

 Courses

 Practice



The goal of this article is to provide a good understanding of the MVC pipeline. The life cycle is basically is
set of certain stages which occur at a certain time.
Application Life Cycle

MVC actually defined in two life cycles, the application life cycle, and the request life cycle.
The application life cycle, in which the application process starts the running server until the time it stops. and it tagged the two
events in the startup file of your application. i.e the application start and end events
This is separate from the request life cycle, which is the sequence of events or stages that executed every time an HTTP request is
handled by the application
MVC Request Life Cycle:
MVC Request Life Cycle

 The Starting point for every MVC application begins with routing. After that, the received request figures out and finds
how it should be handled with the help of the URL Routing Module. The routing module is responsible for matching the
incoming URL to routes that we defined in our application.
 Every route has an associated route handler associated with them. If the request is matched to a route defined in our MVC
application, the MVC Route Handler retrieves an instance of the MVC HttpHandler.
 The MVC Handler Start the process of initializing and executing a controller. The MVC framework handles converting
route data into a specific controller that can handle the requests.
 This is achieved through the MVC components like the Controller Factory and Activators which are responsible for
creating an instance of the Controller class.
 After the controller has been created, A component called the action invoker finds and selects an appropriate Action
method to invoke on our controller.
 Model binding happens before the method is called, which maps the data from our HTTP request to the parameters of our
action methods. Also called action filter before and after action results are generated.
 Now after our action result has been prepared, the next stage triggers, which is Result Execution.
 If the result is a view type, the View Engine will be called and it will find the view and render it.
 If not a view type then the action result will execute on its own. This Result Execution is nothing but generates an actual
response to that original HTTP request.
Lets we see now code end,
The MVC application is the main part of every MVC project. This class is inherited from HttpApplication Class. This class exposes a
number of Request life cycle events that we can attach event handlers to and run our own code.
The application start and ends. These two events run before and after any other events and allow our application to start or stop
receiving the requests.
Application Start :
so every MVC application life starts with an application start event. This event fires when the application receives its first request.
This is the entry point file of the MVC application. This event fires when the application receives its first request.it allows us to
perform global configuration before anything will happen which we can see default implementation here.
As you can see here,

 C#
using System.Web.Mvc;

using System.Web.Optimization;

using System.Web.Routing;

namespace MVC_Application {
public class MvcApplication : System.Web.HttpApplication {

protected void Application_Start()

AreaRegistration.RegisterAllAreas();

FilterConfig.RegisterGlobalFilters(

GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

 In MVC application, you can use this for various tasks like applying global configuration, register script, and CSS
bundles .as you can see here default implements RegisterBundles, RegisterGlobalFilters so on
 The RegisterRoutes method adds any routes that we define to static collection on RouteTable Class. This is the collection
of routes that URL Routing tries to match to incoming URLs.
 We need to define this before anything will happen so that the request has something to be matched. and each of these
routes also needs to have an associated RoutHandler class that will actually process the incoming requests after it’s been
matched to the route. RouteHandler is used to retrieve the right Httphandler for request.
Application End:
This event is fired when our application stops and then no more requests can be received.it is rare to use this event but if you want to
run any task before the application completely shuts down intentionally. This is a good place to do it.
PreApplication Start:
There are some cases in which you want to execute some custom code before the application starts In this situation we have the
option of using the PreApplication Start method. Actually, this method defines on assembly level.
Lets we see every phase in detail:
Controller Initialization:

MVC controller Initialization Flow

The MVCHandler’s,
 The ProcessRequest method is responsible for generating a response to an incoming request. To do this it must create and
execute a controller.
 First, it calls a child method named ProcessRequestInit, which asks a component called the Controller Factory to provide
a Controller for the current request. The Controller Factory selects an appropriate Controller class from the current
application using the passed route data.
 Next, the factory uses a component called the Controller Activator to actually create an instance of that class. The
Controller Activator uses a Dependency Resolver when instantiating the requested class. it allows patterns like dependency
injection to be implemented After the MVCHandler has acquired a Controller from these steps, it calls the Execute method
on that Controller. It’s from within this method that all of the powerful tools like Action methods are exposed and begin
processing.
Action Method Execution Process:
Action Method execution Flow

Next Phase,
 The Action Invoker is responsible for selecting and executing the best method to handle the incoming request.it chooses by
matching route data to method name along with action selector applied to that method.
 once the method has been selected before, it executed the authentication and authorization process. These security steps are
implemented through MVC filters.it is components that allow you to inject logic into the processing pipeline so
 The first authentication, this filter verifies the person if the person is who they say is if authentication fails then it is sent
back to the requestor if it succeeds. we move on to authorization it is checked what the requestor is allowed to do if the
requestor is not authorized it is sent back to the browser.
 if the user passes both phases then the pipeline moves forward so the action invoker has been chosen method to execute
before the method is executed it need to have parameter populated so that’s where model binding comes in. so it is taking
data from the request and use that data to create requestor object. after all parameters for a given method have been passed
then the action invoker is able to call that method. The model binder itself retrieves data to populate the action method
parameter from value providers.
Model Binding Process Flow

 The MVC offers four default providers that collect data from common places that are Form Data, Route Data, Query
String, Files these classes provide information from various sources related to the current requests then an action filter is
executed. it executed two methods i.e OnActionExecuting which fire before the action method
and OnActionExecuted which fire afterward so at this point OnActionExecuting filters are run so after these execution are
done finally action method call itself it return action result in short it determine and prepare the type of response that will
handle the request after that OnActionExecuted filters run this allows us to add logic into the pipeline before the result
executed.
In-build, MVC provides action filters are:
Output Cache: This filter is used to caches the output of action for a certain duration of time.
Handle Error: This filter is used to handles the error caused by an action or controller, if any exception occurs it redirects the action to
a custom error page.
Authorize: This filter is used for filtering the authorized user to access the resource.
Note: we can create a custom filter by implementing that particular filter interface class.
View Result Execution Process:
View Result Execution Flow

Next Phase,
Action result execution is triggered by action invoker before the result execute the associated result filter are run first this

filter also expose two methods.
 The first OnResultExecuting fires before the action result in itself after this method run the execute result of the action
result is called. The MVC provided the different types of action results the execute result provided pipeline branches
between two paths if the result is in view or partial view form then the view engine renders the view and if the result is in
another form then this result generally handles writing the responses out itself.After onResultExecuted method of result
filters are run .this is the last point of MVC to inject your own logic
Action Result Execution Process:
Action Result Execution Flow

Next Phase,
 View rendering process Starts when the Action Invoker calls the ExecuteResult method on that object.
 In the case of View Results, the ExecuteResult method is actually defined on a parent class called ViewResultBase. So the
invoker calls the base class’s ExecuteResult method, which in turn calls an abstract method named FindView. The child
View Result class overrides this method and uses it to ask the View Engine to find the right View. The View Engine
returns a ViewEngineResult, which will contain either the acquired View or a list of locations that it tried to search for one.
Views are nothing more than a class that implements the IView interface, which defines only one method that’s called
Render. Render is the method that finally writes out the contents of our template to the response for the request.
That is all about MVC Life Cycle.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks
Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a
time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out
now!

Filters in ASP.NET MVC


ASP.NET MVC Filters are used to inject extra logic at the different levels of MVC Framework request processing. Filters
provide a way for cross-cutting concerns (logging, authorization, and caching).

In this article, I will show you the different categories of filters that the MVC Framework supports, how to control their
execution, and how to create and use filters. We can create our own custom filters. In every request, your action method in
the controller will have to check if the user was right or authorized to perform the action and view its result.
The ASP.NET MVC Framework supports four different types of filters. Authentication Filters are introduced with ASP.NET MVC
5. Each allows you to introduce logic at different points during request processing.

Filter Type Interface Description


Authentication IAuthenticationFilter These are Runs, before any other filters or the action method.
Authorization IAuthorizationFilter These Runs first, before any other filters or the action method.
Action IActionFilter These Runs before and after the action method.
Result IResultFilter Runs before and after the action result are executed.
Exception IExceptionFilter Runs only if another filter, the action method, or the action resultthrows an exception.

Types of Filters in ASP.NET MVC and their Sequence of Execution


There are five types of Filters in ASP.NET MVC 5:
1. Authentication Filters

Authentication filter runs before any other filter or action method. Authentication confirms that you are a valid or
invalid user. Action filters implement the IAuthenticationFilter interface.

2. Authorization Filters

The AuthorizeAttribute and RequireHttpsAttribute are examples of Authorization Filters. Authorization Filters are
responsible for checking User Access; these implement the IAuthorizationFilterinterface in the framework. These
filters used to implement authentication and authorization for controller actions. For example, the Authorize filter
is an example of an Authorization filter.

3. Action Filters
Action Filter is an attribute that you can apply to a controller action or an entire controller. This filter will be called
before and after the action starts executing and after the action has executed.

Action filters implement the IActionFilter interface that has two methods OnActionExecuting
andOnActionExecuted. OnActionExecuting runs before the Action and gives an opportunity to cancel the Action
call. These filters contain logic that is executed before and after a controller action executes, you can use an
action filter, for instance, to modify the view data that a controller action returns.

4. Result Filters

The OutputCacheAttribute class is an example of Result Filters. These implement the IResultFilter interface which
like the IActionFilter has OnResultExecuting and OnResultExecuted. These filters contain logic that is executed
before and after a view result is executed. Like if you want to modify a view result right before the view is
rendered to the browser.

5. ExceptionFilters

The HandleErrorAttribute class is an example of ExceptionFilters. These implement the IExceptionFilter interface
and they execute if there are any unhandled exceptions thrown during the execution pipeline. These filters can
be used as an exception filter to handle errors raised by either your controller actions or controller action results.
You can override the methods in your controller class if you want.
Creating a new custom Authentication Filter with ASP.NET MVC 5
Note:

The ActionFilterAttribute class implements both the IActionFilter and IResultFilter interfaces. This class is abstract, which
forces you to provide an implementation. The other classes, Authorize Attribute and HandleErrorAttribute, contain useful
features and can be used without creating a derived class.

I’m going to use a custom Authentication filter to set the new principal for the current request, a custom authentication filter
that will simply redirect the user back to the login page if they're not authenticated.
Choose MVC, and click on the “OK” button.
To create an Authentication filter, you must implement the IAuthenticationFilter. I need to create a new folder. Right-click on
to your project and add a new folder.
I named this folder “AuthData”. I need to add a class inside this folder. So right-click on to this folder and add a class.
I have given “AuthAttribute” name to my class.
Click on to “Add” button.

Here, we have derived the AuthAttributeclass from theActionFilterAttribute, IAuthenticationFilter class. I need to resolve it
from the “ActionFiltersinMVC.AuthData” namespace.

public class AuthAttribute : ActionFilterAttribute, IAuthenticationFilter


You can see the following screenshot:
The IAuthenticationFilter interface defines two methods: OnAuthentication and OnAuthenhenticationChallenge. The
OnAuthentication method is executed first and can be used to perform any needed authentication. The
OnAuthenticationChallengemethod is used to restrict access based upon the authenticated user's principal.
ResloveActionFilterAttribute and IAuthenticationFilter form the “using System.Web.MVC.Filters;” namespace.
1. namespace ActionFiltersinMVC.AuthData
2. {
3. public class AuthAttribute: ActionFilterAttribute,
4. IAuthenticationFilter
5. {
6.
7. public void OnAuthentication(AuthenticationContextfilterContext)
8. {
9. //Logic for authenticating a user
10. }
11.
12. //Runs after the OnAuthentication method
13. public void OnAuthenticationChallenge(AuthenticationChallengeContextfilterContext)
14. {
15. //TODO: Additional tasks on the request
16. }
17. }
18. }
In OnAuthentication, I write code for user authentication and in OnAuthenticationChallenge, I write some code for the other
tasks.
You can now test out the AuthAttribute by applying it to the HomeController class. Open up the HomeController class file,
then add using statement for your AuthData namespace:
Here is my Login page, go for the new user registration.

I have used my email address to create a new password and clicked on to “Register” button.
You can see, I’m logged in with my email.
You can also manage your account setting as in the following screenshot:
Authorization Filter
These filters enforce your authorization policy ensuring that action methods can be invoked only by approved users. These
filters are the filters that run before the action method is invoked. These filters implement the IAuthorizationFilter interface,
1. namespace sytem.Web.MVC
2. {
3. Public interface IAuthorizationFilter
4. {
5. Void OnAutorization(AuthorizationContextfilterContext);
6. }
7. }
For the Authorization, let’s make some changes in the “AuthAttribute” class.

This “AuthAttribute” class should inherit by “AuthorizeAttribute” classes. For using the AuthorizeAttribute” class, we need to
add the namespace:

using System.Web.Mvc; .
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.Mvc;
6.
7. namespace ActionFiltersinMVC.AuthData
8. {
9. public class AuthAttribute: AuthorizeAttribute {}
10. }
We override the AuthorizeCore(HttpContextBasehttpContext) method, this ensures that I benefit from the feature build in
Authorize attribute.
The constructor of the filter AuthAttribute (boolallowedParam), takes the bool value indicating whether local requests are
permitted by taking advantage of the building feature of authorization attribute base class, I only have to focus the
authorization logic and return true from the authorize core method.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.Mvc;
6.
7. namespace ActionFiltersinMVC.AuthData
8. {
9. public classAuthAttribute: AuthorizeAttribute
10. {
11. private bool localAllowed;
12. public AuthAttribute(boolallowedParam)
13. {
14. localAllowed = allowedParam;
15. }
16. protected overrideboolAuthorizeCore(HttpContextBasehttpContext)
17. {
18. if (httpContext.Request.IsLocal)
19. {
20. return localAllowed;
21. } else
22. {
23. return true;
24. }
25. }
26. }
27. }
Now open the “Home Controller” and apply some code, In this, I have applied the Authorize attribute filterover the Index()
method. For using the [AuthorizeAttribute] we need to add the namespace “using ActionFiltersinMVC.AuthData;”.
1. using ActionFiltersinMVC.AuthData;
2. public class HomeController: Controller
3. {
4. [AuthorizeAttribute]
5. public ActionResult Index()
6. {
7. return View();
8. }
And in the About action method, we simply print a message.
1. using ActionFiltersinMVC.AuthData;
2. using System;
3. using System.Collections.Generic;
4. using System.Linq;
5. using System.Web;
6. using System.Web.Mvc;
7.
8. namespace ActionFiltersinMVC.Controllers
9. {
10. public class HomeController: Controller
11. {
12. [AuthorizeAttribute]
13. public ActionResult Index()
14. {
15. return View();
16. }
17. public ActionResult About()
18. {
19. ViewBag.Message = "Hello...Nitin";
20. return View();
21. }
22. }
23. }
Here is the screenshot of Controller:
Now save the project and run the project by pressing F5. You’ll redirect on to the login page.
Enter the Email and password to login to the account; I have registered myself in the Authentication filters part, so there is
no need for the new registration.

Click on to the “Log in” button.


After login, you will be redirected on to the home page.
I’m going to use Authorize filter, if I’m using Authorize attribute, only authenticated users can access About() method.
1. using ActionFiltersinMVC.AuthData;
2. using System;
3. using System.Collections.Generic;
4. using System.Linq;
5. using System.Web;
6. using System.Web.Mvc;
7.
8. namespace ActionFiltersinMVC.Controllers
9. {
10. public class HomeController: Controller
11. {
12. //[AuthorizeAttribute]
13. public ActionResult Index()
14. {
15. return View();
16. }
17.
18. [Authorize]
19. public ActionResult About()
20. {
21. ViewBag.Message = "Hello...Nitin";
22. return View();
23. }
24. }
25. }
Now build the application and run it and try to access the about page, here you can see if I log in to About page

You can see About page:


Here in the below screenshot, I have accessed the About action method.
You can specify users, which are only able to see the About page as in the following screenshot.

Here I pass two email ids, for the authorized users.


Now, create a new user, it must be a new user and create a password for the new user.

Click on to “Register” button.


You can see it’s automatically logged in to the application,
Now I’m trying to access the “About” page.
So, we are unable to access the “About” page because you have to authorize access to the about page by only two ids, which
is authorized for the About action.
Action Filters
There are the following action filters,
 Output Cache: This action filter caches the output of a controller action.
 Handle Error: This action filter handles errors raised when a controller action executes.
 Authorize: This action filter enables you to restrict access to a particular user or role.
Output Cache

Example: Specifies the return value to be cached for 5 seconds.


1. public class ActionFilterDemoController: Controller
2. {
3. [HttpGet]
4. [OutputCache(Duration = 5)]
5. public string Index()
6. {
7. return DateTime.Now.ToString("T");
8. }
9. }
Handle Error

If any error occurs during the action execution, it will find a view named Error in the Views folder and render that page to the
user

Example:

Redirect application to a custom error page when an error is triggered by the controller
1. [HandleError]
2. public class ActionFilterDemoController: Controller
3. {
4. public ActionResult Index()
5. {
6. throw new NullReferenceException();
7. }
8. public ActionResult About()
9. {
10. return View();
11. }
12. }
Authorize

Example: Allowing only authorized users to log in the application.


1. public class ActionFilterDemoController: Controller
2. {
3. [Authorize]
4. public ActionResult Index()
5. {
6. ViewBag.Message = "This can be viewed only by authenticated users only";
7. return View();
8. }
9. [Authorize(Users = "nitinoandit.00@gmail.com")]
10. public ActionResultMyIndex()
11. {
12. ViewBag.Message = "Only Nitin Pandit can view";
13. return View();
14. }
15. }

Result Filters
Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult,
PartialViewResult, RedirectToRouteResult, which derives from the ActionResult class.

Example:
1. public interface IResultFilter
2. {
3. void OnResultExecuted(ResultExecutedContextfilterContext);
4. void OnResultExecuting(ResultExecutingContextfilterContext);
5. }

Exception Filters
Exception filters are run only if an unhandled exception has been thrown when invoking an action method. An exception
may be for the following reasons:
 Action method itself.
 When the Action result is executed.
 Another kind of filter.
Example:
1. Public interface IExceptionFilter
2. {
3. void OnException(ExceptionContextfilterContext);
4. }
First, you need to create a RangeError.html page file within the “Content” folder in our application; we will use this file to
display a simple message.
Give the name to the page, and click on to the “OK” button.
Here's the screenshot:
Here, we have derived the AuthAttribute class from the FilterAttribute class, in addition to implementing the IExceptionFilter.
For using the FilterAttribute and IExceptionFilter you need to use “using System.Web.Mvc;” namespace in your MVC
Application.

This exception filter is handling the instance by redirecting the user browser to a file called RangError.html in the content
folder, In the ExceptionHandled method we checked the exception is not properly handled and Exception type is
ArgumentOutOfRangeException then,
1. filterContext.Result = new RedirectResult("~/Content/RangeError.html");
2. filterContext.ExceptionHandled = true;
The page will be redirected to a custom error page which we have created in RangeError.html page in the content folder.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.Mvc;
6.
7. namespace ActionFiltersinMVC.AuthData
8. {
9. public class AuthAttribute: FilterAttribute,
10. IExceptionFilter
11. {
12. public void OnException(ExceptionContextfilterContext)
13. {
14. if (!filterContext.ExceptionHandled && filterContext.ExceptionisArgumentOutOfRange
Exception) {
15. filterContext.Result = newRedirectResult("~/Content/RangeErrorPage.html");
16. filterContext.ExceptionHandled = true;
17. }
18.
19. }
20. }
21.
22. }

In the home controller I have written down a method TestRange, this method throws ArgumentOutOfRangeException.
Now, I am going to run the application, we can see the default exception handling.

You might also like