0

I founded some articles in here and I try customize authorize using seesion, but seem it's not work fine. Notes, I code hard in authorize with pass parameter from session. This is my code snippet. Example:

[RMSAuthorize]
public ActionResult TopicDetail()
{
    return View();
}

And this is custom authorize

 public class RMSAuthorize : AuthorizeAttribute  
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //get Group_ID from session when user login success
            //if user not login then session is NULL
            var GID = (HttpContext.Current.Session["CurrentUser"] as USER).Group_ID;
            if (GID = "G0001")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

Ok, when build, I get error at var GID = (HttpContext.Current.Session["CurrentUser"] as USER).Group_ID; as Object reference not set to an instance of an object Can you tell me what problem in here ? I wrong or mistake some anything and how to fix it ? .Thank you so much.

Brian Crist
  • 806
  • 3
  • 16
  • 42
  • Also take a look at [this](http://stackoverflow.com/questions/30372022/authorization-with-session-variables-in-asp-net-mvc-5) SO answer. – kayess Jan 11 '16 at 15:21
  • Dear @kayess , i hard code `[RMSAuthorize]` using parameter as session, not using rolename. Thank you – Brian Crist Jan 11 '16 at 15:30
  • Did you try to use `HttpContext.Current.Session` ? – kayess Jan 11 '16 at 15:33
  • Yes , I add `HttpContext.Current.Session` , but when run , it not working @@ – Brian Crist Jan 11 '16 at 15:38
  • Please edit your question with the modified code and with error description if exist. – kayess Jan 11 '16 at 15:50
  • Ok , I edited, When run as above , i get error `Object reference not set to an instance of an object.` as line `var GID = (HttpContext.Current.Session["CurrentUser"] as USER).Group_ID;` . I think i should check it first , `if (GID != null ) return false else {}` . – Brian Crist Jan 11 '16 at 15:57
  • I would first check to see if the Session and the variable you look for exists, then the casted objects `Group_ID` property. And a final note, whenever you post to SO, you should always debug firstly to see what might be wrong. – kayess Jan 11 '16 at 16:03

0 Answers0