Using Action Filters on MVC C# using query String

Tharindu Lakshitha picture Tharindu Lakshitha · May 15, 2012 · Viewed 16.8k times · Source

Im using class name RightCheckerAttribute to check user permission in MVC3 application... So the RightCheckerAttribute class is like this...

    public bool isAdmin { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContextBase context = filterContext.HttpContext;

        bool result = Convert.ToBoolean(context.Request.QueryString["isAdmin"].ToString());

        if (isAdmin != result) 
        {
            RouteValueDictionary redirecttargetDictionary = new RouteValueDictionary();
            redirecttargetDictionary.Add("action", "NoPermission");
            redirecttargetDictionary.Add("controller","Singer");
            filterContext.Result = new RedirectToRouteResult(redirecttargetDictionary);

        }

        //base.OnActionExecuting(filterContext);
    }

So in Method i applying this have head as..

[RightChecker (isAdmin=true)]

Im Executing this method as this..

http://localhost:5576/Singer/DeleteSinger?isAdmin=true

The problem is whether I'm passing true or false... I got result variable as false... And I'm getting:

Exception[Null Object references]...

Answer

Prashanth Thurairatnam picture Prashanth Thurairatnam · May 15, 2012

It seems you are not passing the isAdmin=false or isAdmin=true in your query string. It works for me. However you will need to handle the situation where you are not passing the querystring parameter. Check my implementation. As mentioned in the comments section of the question, it is not secured enough to pass this through a query string.

        public class RightChecker : ActionFilterAttribute
        {
            public bool IsAdmin;            

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {

               bool result = false;
               if (filterContext.HttpContext.Request.QueryString["isAdmin"] != null)
               {
                       bool.TryParse(filterContext.HttpContext.Request.QueryString["isAdmin"].ToString(), out result);
               }

               if (IsAdmin != result) 
               {
                   //your implementation
               }
            }
        }

Your action method

    [RightChecker(IsAdmin=true)]
    public ActionResult AttCheck()
    {
        return View();
    }