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

ASP.NET MVC Interview Questions and Explanations

1) Data annotations are attribute classes under the namespace _______________.

  1. System.DataAnnotations
  2. System.Annotations
  3. System.ComponentModel.DataAnnotations
  4. System.Component

Answer:  c

Explanation: The Data annotations attribute classes are available under the namespace System.ComponentModel.DataAnnotations.

2) The validation rules are implemented in _____________.

  1. Controller
  2. Model
  3. View
  4. None of the Above.

Answer:  b

Explanation: We’ll implement these rules on our model object – and not within our Controller or our View.  The benefit of implementing the rules within model object is that this will ensure that the validation will be enforced via any scenario within our application that uses the model object.  This will help ensure that we keep our code DRY and avoid repeating rules in multiple places.

3) Among the following which script files are required for enabling client side validations?

  1. jquery.validate-vsdoc.js
  2. jquery.validate.min.js
  3. jquery.validate.js
  4. jquery.validate.unobtusive.min.js

Answer:  b and d.

Explanation: For client side validation to work, you will need to ensure that these two <SCRIPT> tag references are in your view:

<scriptsrc=”@Url.Content(“~/Scripts/jquery.validate.min.js”)”type=”text/javascript”></script>
<scriptsrc=”@Url.Content(“~/Scripts/jquery.validate.unobtrusive.min.js”)”type=”text/javascript”></script>

These can be added by writing the following in .cshtml file

@Scripts.Render(“~/bundles/jqueryval”)

4) Client Validations can be turned off by

  1. Removing the Data annotation attributes from the Model Class.
  2. By adding @{  Html.EnableClientValidation(false); } in the view page.
  3. By adding @{ Html.EnableClientValidation = false; } in the view page.
  4. None of the Above.

Answer:  b

Explanation: To turn off client side validation in view we need to add following

@{  Html.EnableClientValidation(false); }

5) Explain the reason why we use Metadata Class?

Answer: To provide metadata for properties that you don’t have control over, you can create a separate metadata class that has those same property names. You can tell the framework to use this class instead of your model object by providing the [Metadata Type] attribute.