MVC .Net Architecture



Diff between Api Controller and Controller

  • The first major difference you will notice is that actions on Web API controllers do not return views, they return data.



State ManagementExample Project 




ViewData
1. ViewData is derived from the ViewDataDictionary class and is basically a Dictionary object i.e. Keys and Values where Keys are String while Values will be objects.
2. Data is stored as Object in ViewData.
3. While retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.
4. ViewData is used for passing value from Controller to View.
5. ViewData is available only for Current Request. It will be destroyed on redirection.



ViewBag
1. ViewBag is a Wrapper built around ViewData.
2. ViewBag is a dynamic property and it makes use of the C# 4.0 dynamic features.
3. While retrieving, there is no need for Type Casting data.
4. ViewBag is used for passing value from Controller to View.
5. ViewBag is available only for Current Request. It will be destroyed on redirection.



TempData
1. TempData is derived from the TempDataDictionary class and is basically a Dictionary object i.e. Keys and Values where Keys are String while Values will be objects.
2. Data is stored as Object in TempData.
3. While retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.
4. TempData can be used for passing value from Controller to View and also from Controller to Controller.
5. TempData is available for Current and Subsequent Requests. It will not be destroyed on redirection.




https://www.c-sharpcorner.com/article/filters-in-Asp-Net-mvc-5-0-part-twelve/

E:\Web Doc\interview Preparations\@Projects\FiltersDemo

You can override the methods in your controller class if you want.

table



















Authentication Filters

This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create CustomAuthentication filter. The definition of this interface is given below-
public interface IAuthenticationFilter
{
 void OnAuthentication(AuthenticationContext filterContext);

 void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below-
public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
 public void OnAuthentication(AuthenticationContext filterContext)
 { 
 //Logic for authenticating a user
 }
 //Runs after the OnAuthentication method
 public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
 { 
 //TODO: Additional tasks on the request
 }
}

Authorization Filters

The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-
public interface IAuthorizationFilter
{
 void OnAuthorization(AuthorizationContext filterContext);
}
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
 protected virtual bool AuthorizeCore(HttpContextBase httpContext);
 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
 public virtual void OnAuthorization(AuthorizationContext filterContext);
 protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
}
In this way you can make your CustomAuthorize filter attribute either by implementing IAuthorizationFilter interface or by inheriting and overriding above methods of AuthorizeAttribute class.

Action Filters

Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.
public interface IActionFilter
{
 void OnActionExecuting(ActionExecutingContext filterContext);
 void OnActionExecuted(ActionExecutedContext filterContext);
}

Result Filters

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.
public interface IResultFilter
{
 void OnResultExecuted(ResultExecutedContext filterContext);
 void OnResultExecuting(ResultExecutingContext filterContext);
}


Exception Filters

Exception filters are executed when exception occurs during the actions execution or filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.
public interface IExceptionFilter
{
 void OnException(ExceptionContext filterContext);
}

Order of Filter Execution

All ASP.NET MVC filter are executed in an order. The correct order of execution is given below:
  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters


Configuring Filters

You can configure your own custom filter into your application at following three levels:
  1. Global level

    By registering your filter into Application_Start event of Global.asax.cs file with the help of FilterConfig class.
    protected void Application_Start()
    {
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
    
  2. Controller level

    By putting your filter on the top of the controller name as shown below-
    [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
     //
    }
    
  3. Action level

    By putting your filter on the top of the action name as shown below-
    public class UserController : Controller
    {
     [Authorize(Users="User1,User2")]
     public ActionResult LinkLogin(string provider)
     {
     // TODO:
     return View();
     }
    }


ViewData

ViewData is a dictionary object, a property of the ControllerBase class. It is derived from ViewDataDictionary and is accessed by a string key. ViewData is used to transfer data from the controller to a view. ViewData can be passed in the form of a key-value pair. Type casting is required when fetching data from ViewData; be sure to check for null values to avoid errors.
To demonstrate ViewData, I have created the following View:
  1. @using MySampleDataInMVC.Models
  2. @{
  3. ViewBag.Title = "Employee Details";
  4.  
  5. }
  6.  
  7. <h2>Employee Details</h2>
  8.  
  9. <div>
  10. <h4>Employee</h4>
  11. <hr />
  12. <dl class="dl-horizontal">
  13. @{
  14. var EmployeeDetail = ViewData["EmployeeDetail"] as Employee;
  15. }
  16.  
  17. </dl>
  18. <h2> @ViewData["Message"] </h2>
  19. <br />
  20. <p>EmployeeID Id : @EmployeeDetail.EmployeeID </p>
  21. <p>EmployeeID Name : @EmployeeDetail.EmployeeName </p>
  22. <p>EmployeeID Department : @EmployeeDetail.Department </p>
  23. </div>
The following Controller action method passes data to the View:
  1. using MySampleDataInMVC.Models;
  2. using System.Web.Mvc;
  3.  
  4. namespace PassingDataInMVC.Controllers
  5. {
  6. public class EmployeeController : Controller
  7. {
  8. // GET: Student
  9. public ActionResult Index()
  10. {
  11. Employee model = new Employee()
  12. {
  13. EmployeeID = 1,
  14. EmployeeName = "Tapas Pal",
  15. Department = "Information Technology"
  16. };
  17. ViewData["EmployeeDetail"] = model;
  18. ViewData["Message"] = "This is to print Employee Details
  19. using ViewData";
  20. return View();
  21. }
  22. }
  23. }

ViewBag

ViewBag is used to pass data from the controller to the view for a single request. ViewBag is a dynamic type collection. The life of ViewBag persists during the current request. It's a wrapper around the ViewData and also is used to pass data from the controller to the corresponding view. During the redirection, ViewBag's value becomes null.  To retrieve ViewBag, data typecasting is not required. Refer to the following ViewBag syntax:
  1. ViewBag.name=value;
  2. ViewContext.ViewBag.name=value;
  3. ViewContext.Controller.ViewBag.name=value;
The following example demonstrates ViewBag by displaying employee information.

View Code

  1. @{
  2. ViewBag.Title = "Employee Details";
  3. }
  4.  
  5. <h2>Employee Details</h2>
  6.  
  7. <div>
  8. <h4>Employee</h4>
  9. <hr />
  10. <dl class="dl-horizontal">
  11. @{
  12. var employeeDetail = ViewBag.EmployeeDetail;
  13. }
  14.  
  15. </dl>
  16. <h2> @ViewBag.Message </h2>
  17. <br />
  18.  
  19. <p>Employee Id : @employeeDetail.EmployeeID</p>
  20. <p>Employee Name : @employeeDetail.EmployeeName</p>
  21. <p>Employee Department : @employeeDetail.Department</p>
  22.  
  23. </div>

Controller Code

The following Controller action method passes data to the View:
  1. using MySampleDataInMVC.Models;
  2. using System.Web.Mvc;
  3.  
  4. namespace MySampleDataInMVC.Controllers
  5. {
  6. public class EmployeeController : Controller
  7. {
  8. // GET: Student
  9. public ActionResult Index()
  10.  
  11. {
  12. Employee model = new Employee()
  13. {
  14. EmployeeID = 1,
  15. EmployeeName = "Tapas Pal",
  16. Department = "Information Technology"
  17. };
  18. ViewBag.EmployeeDetail = model;
  19. ViewBag.Message = "This is to print Employee Details
  20. using ViewBag";
  21.  
  22. return View();
  23. }
  24. }
  25. }

TempData

TempData is a dictionary object. It's a property of the ControllerBase class derived from the TempDataDictionary class. The TempData syntax is the following:
  1. public TempDataDictionary TempData { get; set; }
By using TempData, you can pass data from one controller to another controller or Action to Action. The following View example explains the TempData usage:

View Code

  1. @using MySampleDataInMVC.Models
  2. @{
  3. ViewBag.Title = "Employee Details";
  4. }
  5.  
  6. <h2>Employee Details</h2>
  7.  
  8. <div>
  9. <h4>Employee</h4>
  10. <hr />
  11. <dl class="dl-horizontal">
  12. @{
  13. var EmployeeDetail = TempData["EmployeeDetail"] as
  14. Employee;
  15. }
  16.  
  17. </dl>
  18. <h2> @TempData["Message"] </h2>
  19. <br />
  20. <p>Employee Id : @EmployeeDetail.EmployeeID</p>
  21. <p>Employee Name : @EmployeeDetail.EmployeeName</p>
  22. <p>Employee Department : @EmployeeDetail.Department</p>
  23. </div>
The following Controller code explains passing data to the View:

Controller Code

  1. using MySampleDataInMVC.Models;
  2. using System.Web.Mvc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Web;
  7.  
  8. namespace PassingDataInMVC.Controllers
  9. {
  10. public class EmployeeController : Controller
  11. {
  12. // GET: Student
  13. public ActionResult Index()
  14. {
  15. Employee model = new Employee()
  16. {
  17. EmployeeID = 1,
  18. EmployeeName = "Tapas Pal",
  19. Department = "Information Technology"
  20. };
  21. TempData["EmployeeDetail"] = model;
  22. TempData["Message"] = "This is to print Employee Details
  23. using TempData";
  24. return View();
  25. }
  26. }
  27. }





 Filters Deep Example Project








Comments

Popular Posts