C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ASP.NET MVC Action FiltersThe MVC framework provides the filter attribute so that we can filter the user requests. We can apply it to an individual action or an entire controller. It completely modified the way in which an action is called. The ASP.NET MVC Framework provides the following action filters. OutputCache: it makes controller's action output cacheable for the specified time. HandleError: It is used to handle error raised when a controller action executes. Authorize: It allows only authorize user to access resources. OutputCache ExampleHere, we are implementing OutputCache that will cache the action method output for the specified time. The action code is given below: // MusicStoreController.csusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplicationDemo.Controllers { public class MusicStoreController : Controller { [OutputCache(Duration =10)] public ActionResult Index() { return View(); } } } It renders an index file that has the following code. // index.cshtml<h4> @{ Response.Write( DateTime.Now.ToString("T")); } </h4> Output: It produces the following output and cache that for 10 seconds. It will not change before 10 seconds even we refresh the web page again and again. Authorize ExampleNow, we are applying authorize attribute to the action method, the code is given below. // MusicStoreController.csusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplicationDemo.Controllers { public class MusicStoreController : Controller { [Authorize] public ActionResult Index() { return View(); } } } Output: This attribute will restrict unauthorized user access. The application redirects to the login page for authentication.
Next TopicASP.NET MVC Model
|