How to make a filter before executing action?

-1

Before running action, I want to make a filter to check if the value exists.

If the value does not exist, return to specific page (Index, Home).

Any solution?

    
asked by anonymous 17.02.2017 / 00:38

1 answer

1

You can use Action Filters to do this. An Action Filter is an attribute that you place on top of each action (or in the controller, to apply to all actions) indicating to the framework that, before executing the action, it must execute its filter. Try the code below:

Home controller code:

using MvcApplication1.ActionFilters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{

    public class HomeController : Controller
    {

        [MeuFilter]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Filter Code:

using System;
using System.Diagnostics;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1.ActionFilters
{
    public class MeuFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpSessionStateBase session = filterContext.HttpContext.Session;
            Controller controller = filterContext.Controller as Controller;

            if (controller != null)
            {
                if (session["Login"] == null)
                {
                    controller.HttpContext.Response.Redirect("/Home/About");
                }
            }

        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // Implementar
        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            // Implementar
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            //Implementar
        }
    }
}

Before executing the action Index, "MyFilter" will be executed, and in it I am checking a login session, if it does not exist, it redirects to another action. To create an Action Filter, you must inherit the ActionFilterAttribute class and implement the IActionFilter interface. For more details I suggest reading this article

    
17.02.2017 / 01:08