17Feb

Filters and Attributes in ASP.NET MVC

Filters inject extra logic into MVC Framework request processing. They provide a simple and elegant way to implement cross-cutting concerns. This term refers to functionality that is used all over an application and doesn’t fit neatly into one place, where it would break the separation of concerns pattern.

For example, if we need some action to be executed when the user has been authenticated then we can adorn the action with the [Authorize]attribute. This will take care of calling the attribute class which implements the authorization filter to check whether the user  is authorized or not.

[Authorize]

public ActionResult Index()

{

    return View();

}

  

Four Basic Types of Filters

The MVC Framework supports four different types of filters. Each allows you to introduce logic at different points during request processing.

 

filter-type

 

Using Authorization Filters

Let us create a MVC project with the following code in the Home controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Filters.Controllers 
{
public class HomeController : Controller 
{
public string Index() 
{
return "This is the Index action on the Home controller";
}
}
}

Authorization filters are the filters that are run first before the other kinds of filters and before the action method is invoked. As the name suggests, these filters enforce your authorization policy, ensuring that action methods can be invoked only by approved users. Authorization filters implement the IAuthorizationFilter interface.

Before applying Authorization filters if we run the project we will see the following output.

bngfj

 

 Now let us add a new Infrastructure folder and create a new class called CustomAuthAttribute.cs  within it and write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Filters.Infrastructure 
{
public class CustomAuthAttribute : AuthorizeAttribute 
{
private bool localAllowed;
public CustomAuthAttribute(bool allowedParam) 
{
localAllowed = allowedParam;
}
protected override bool AuthorizeCore(HttpContextBase httpContext) 
{
if (httpContext.Request.IsLocal) {
return localAllowed;
} 
else 
{
return true;
}
}
}
}

This is a simple Authorization filter. It allows you to prevent access to local requests. This is the simplest method to create authorization filters, which is to subclass the AuthorizeAttribute class and then override the AuthorizeCore method. This ensures that we benefit from the features built in to AuthorizeAttribute. The constructor for our filter takes a bool value, indicating whether local requests are permitted.

 

Applying the Custom Authorization Filter

To use the custom authorization filter, we just add an attribute to the action methods or the controllers.

In the above example we will add this attribute to the Index action method in the Home controller as shown below.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Filters.Infrastructure;
namespace Filters.Controllers 
{                                                                         
public class HomeController : Controller 
{
[CustomAuth(false)]
public string Index() {
return "This is the Index action on the Home controller";
}
}
}

We have set the constructor argument for the filter to false, which means that local requests will be denied access to the Index action method

When we run this on our local system we will get an Http error 401 which says unauthorized. The filter will authorize the request if we make a request from a browser running on other machine or if we set the CustomAuth attribute to true and restart the application.

Related

Token Based Authentication for Web API's

Securing ASP.NET Web API using Custom Token Based AuthenticationProviding a security to the Web API&...

Read More >

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Asynchronous actions in MVC 5

What does it mean?Asynchronous actions allow developers to handle more concurrent requests and can b...

Read More >

ELMAH Integration in ASP.NET MVC Application

ELMAH(Error Logging Modules And Handlers)What is ELMAH?ELMAH (Error Logging Modules and Handlers) is...

Read More >

Unit testing in .NET

Unit Testing – ExplainedA process which involves writing code to verify a system at a lower an...

Read More >

THE RAZOR VIEW ENGINE IN MVC

View Engine is responsible for rendering the view into html form to the browser.ASP.NET MVC includes...

Read More >

ViewData and ViewBag in MVC

ASP.NET MVC provides us two options ViewData and ViewBag for passing data from controller to view.Vi...

Read More >

Creating a Simple Form with Validation Using ASP.NET MVC 4 Empty Template

There are multiple Validation attributes available in MVC. Validation attributes comes from System.C...

Read More >

Brief Journey to Asp.Net MVC Framework

Introduction: ASP.NET MVC is a  framework for building web applications that uses the mode...

Read More >

Share

Comments

Hello Apoorva, the above mentioned content is informative and so useful. I’m trying to find some .Net MVC blogs and I found this post very perfect. Keep coming with more such informative article. Would love to follow them.
12/19/2017 3:02:44 PM | Reply

Post a Comment

  • Recent
  • Popular
  • Tag
Tags
Monthly Archive
Subscribe
Name

Contact Us
  • *
  • *