Action Filters are the attributes in asp.net and using for the controller. it is derived from System.Attribute. The action filter has mainly three filters
- Output Cache
- Handle Error
- Authorize
Example for Output Cache :
public class AllTechGeeksController : Controller
{
[HttpGet]
[OutputCache(Duration = 20)]
public string resultView()
{
return DateTime.Now.ToString("ATG");
}
}
|
---|
Example for Handle Error :
[HandleError]
public class AllTechGeeksController : Controller
{
public ActionResult HomeTest()
{
throw new NullReferenceException();
}
public ActionResult Test()
{
return View();
}
}
|
---|
Example for Authorize :
public class AllTechGeeksController : Controller
{
[Authorize]
public ActionResult TestAllTechGeeks()
{
ViewBag.Message = "Authencated
Users Only";
return View();
}
[Authorize(Roles = "HR")]
public ActionResult HRModule()
{
ViewBag.Message = "Only for HR
department";
return View();
}
}
|
---|
How to create a custom action filter in asp.net MVCCustom filter inherits from ActionFilterAttribute Class in asp.net MVC.and overrides minimum any one of the following methods.
- OnActionExecuting
- OnActionExecuted
- OnResultExecuting
- OnResultExecuted
we can declare the custom action filters in 3 levels
Create a simple Custom Action Filter in Asp.net
- At Global Levele
- At Controller Level
- At Action Level
Create a simple Custom Action Filter in Asp.net
using System;
using System.Web.Mvc;
using System.Diagnostics;
namespace webAppAlltechGeeks
{
public class AllTechGeeksFilter : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{ //You may ot not fetch data from database
here
context.Controller.ViewBag.GreetMesssage = "Hello All Tech
Geeks";
base.OnResultExecuting(context);
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var controllerName = context.RouteData.Values["controller"];
var actionName = context.RouteData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", "onactionexecuting",
controllerName,
actionName);
Debug.WriteLine(message, "Action Filter
Log");
base.OnActionExecuting(context);
}
public override void OnResultExecuting(ResultExecutingContext context)
{
//Write your code here }
public override void OnResultExecuting(ResultExecutingContext context)
{
//Write your code here
}
}
}
|
---|
Post a Comment (0)