ASP.Net MVC 5./ Filter Overrides

Filter Overrides in ASP.Net MVC 5.X

 

Filter Overrides in ASP.NET MVC 5 are very useful when we are implementing a global or controller level filter and we do not want to apply an action filter on some Action methods in the controller. This feature is useful for removing the headache of applying filters for each and every action where we need to exclude only a few actions. For following five types of filters available with MVC:

1.Authentication filters
2.Authorization filters
3.Action filters
4.Result filters
5.Exception filters

We have five type filter overrides corresponding to this:
– OverrideAuthenticationAttribute
– OverrideAuthorizationAttribute
– OverrideActionFiltersAttribute
– OverrideResultAttribute
– OverrideExceptionAttribute

We can mark any action method with an override filter attribute that essentially clears all filters in an upper scope (in other words controller level or global level).

Example: In the following example, the Authorize Filter is applied at the controller level.So, all the action methods of the Home controller can be accessed by the Admin user only. Now I want to exclude the Authorize Filter from the “About” method.

So in this case we can mark this “About” method with the “OverrideAuthorization” attribute. Now all the action methods of the home controller can be accessed by the Admin user except the “About” method. We can access the “About” action method without any authorization.

[Authorize(Users=”John”)]
     public class HomeController : Controller
              { public ActionResult Index() 
                                {
                                  return View(); 
                                        } 
                           [OverrideAuthorization]
                           public ActionResult About() 
                                              { 
                                                      return View(); 
                                                 }
                                                     } 

Note: The OverrideAuthorizationAttribute does not work properly with MVC version 5.0 due to some internal bug. This bug was resolved in MVC version 5.1 (preview).

Cancelling Filter Execution:

1. You can cancel filter execution in the OnActionExecuting methods by setting the Result property to a non-null value.

a. Any pending OnActionExecuted and OnActionExecuting filters will not be invoked
b.Invoker will not call the OnActionExecuted method for the canceled filter or for pending filters.
c.The OnActionExecuted filter for previously run filters will run.
d.All of the OnResultExecuting and OnResultExecuted filters will run.

2. You can cancel filter execution in the OnResultExecuting methods by setting the Cancel property true.
a. Any pending OnResultExecuted and OnResultExecuting are canceled and blank o/p is rendered to browser.
b. The OnResultExecuted filter for previously run filters will run.

 public class Log2Attribute : ActionFilterAttribute

                      {

                          public override void OnActionExecuting(ActionExecutingContext filterContext)

                               {

                                 //filterContext.Result = new EmptyResult();
                                 Trace(“On Action Executing”, filterContext.RouteData);

                            }

                  public override void OnActionExecuted(ActionExecutedContext filterContext)
                               {

                                Trace(“On Action Executed”, filterContext.RouteData);

                            } 
                 public override void OnResultExecuting(ResultExecutingContext filterContext)

                        {

                            filterContext.Cancel = true;
                                  //filterContext.HttpContext.Response.Write(“Advertisement <hr>”);
                                   Trace(“On Result Executing”, filterContext.RouteData);
                        }

             public override void OnResultExecuted(ResultExecutedContext filterContext)
                        {

                            //filterContext.HttpContext.Response.Write(“<hr>Advertisement”);
                             Trace(“On Result Executed”, filterContext.RouteData);

                      }
               public void Trace(string methodName, RouteData routeData)
                     {

                          string colName, actionName;

                          colName = routeData.Values[“controller”].ToString();
                             actionName = routeData.Values[“action”].ToString();
                         string str = string.Format(“2 – Method Name={0}, Controller Name={1},Action={2}”, methodName, colName, actionName);
                         System.Diagnostics.Trace.WriteLine(str);
                        HttpContext.Current.Response.Write(“<br>” + str + “<br>”);

                      } 

                 }

self paced learning on ASP.NET MVC 5.2

 

MVC-Action Selectors

Action Selectors HttpGet and HttpPost

Action Selectors

When the MVC Framework is selecting one of the controller public methods to invoke as an action, it will use any action selector attribute that might be present to define the correct action to invoke.

1. ActionName

2. AcceptVerbs

  • HttpPost
  • HttpGet

ActionName: When we apply this to a controller action it will specify the action name for that method. For the Index method we have bellow we no longer reach this method as action name “Index”. We have to reach this method as “Start”. (http://localhost:123/Home/Start)

[ActionName(“Start”)]
public ActionResult Index()
{
ViewBag.Message = “Welcome to Deccansoft!”;
return View();
}
Note: A view by name “Start” must be added. Index view will not work.

*Can be used if the URL has “_” or “-“ and method doesn’t have the same.

*Also useful when method names and parameters are same for both HTTPGet and HTTPPost.

Also
[ActionName(“GetCSVFileContent”)]

public ActionResult GetCSV()
{
string csv = CreateCSV();
return new ContentResult() { Content = csv, ContentEncoding =
System.Text.Encoding.UTF8, ContentType = “text/csv” };
}

AcceptVerbs: Http verbs allow us to reach a particular action we can say action method is reachable with:

1. [HttpGet] or [AcceptVerbs(HttpVerbs.Get)]

2. [HttpPost] or [AcceptVerbs(HttpVerbs.Post)]

3. [RequireHttps] – Forces the Http request to be resent over Https.

HttpGet: Only get request will be served by action method.

[HttpGet]
public ActionResult LogOn()
{
return View();
}

HttpPost: Only post request will be served by the action method.

In View: @{ Html.BeginForm(); }

<input type=”submit” value=”Submit” /> @{ Html.EndForm(); }

In Controller:

[HttpPost()]

public ActionResult Index(FormCollection col)

{
ViewBag.Greetings1 = “Posted”;
return View();
}

 


Learn Complete ASP.NET MVC 5.2

Understanding ASP.NET MVC?

This article is for the beginners who do not have much idea about MVC. As a beginner all you’ll be knowing is that MVC is a pattern but how do we develop applications using this MVC pattern.

Introduction:

So before understanding what MVC is lets understand first what ASP.NET is?

So ASP.NET is a framework which creates web pages and web sites with the help of html, css, and javascript and severs script.

ASP.NET supports 3 development models:

  1. Web Pages
  2. MVC
  3. Web Form

 

MVC (Model View Controller):

MVC is one of the development models of ASP.NET.

  • The Model represents the data of application (database records)
  • The View displays the data
  • The controller handles the flow of data

MVC Model defines application within 3 logic layers.

  • Input logic(Controller handles Input Logic)
  • Business Logic(Model  handles logic of application data)
  • UI Logic(View display the application data)

 

Model:

I.            This part of application manages data of the application or state of data, i.e. basically model object retrieves data from database.

II.            There is no fixed size or shape of model object because data of one application may not be same as other application.

III.            It includes Validation logic, business logic  and data access logic of an application

E.g. Student object (Model) might retrieves information from database, do some operation on it, validate it and then update information back to Student table in database.

 

Controller:

This part of application controls the flow of application data. Basically it reads from a view, control user input and sends data to model.

 

View:

This part of application display the data, basically it creates UI for data from model and display the data

E.g.: Edit View for Student table that displays textboxes, dropdown list and checkbox on the current state of a Student object.

Advantage:

I.            MVC helps in managing complex task by focusing on one aspect at time, a developer can work on model without depending on views or controller.

II.            Separating the view from rest of application logic enables changing of view technology in future without affecting the rest of the application.

E.g. Client might want view in Silverlight or HTML5

 

MVC vs Traditional Web Form:

I.            It is lighter than Web from because it does not use view state or server based forms or server controls.

II.            It provides better support for test-driven development (TDD)

III.            It has integrated with all existing Asp.net features like Routing, Master Page, Security and Authentication.

So I hope this article has given you a brief idea about what exactly ASP.NET MVC is…..