Search code examples
c#asp.net-mvcsessionauthenticationdata-annotations

How to access Session from a custom data annotation in an ASP.NET MVC project?


For some experimental/exercise purposes, I'm trying to implement a primitive login system before proceeding to Identity services.

My idea was creating a custom data annotation -just like [Authorize] of Identity- and passing inputted form data carried by Session[]. Hence, I would use my custom annotation to authorize certain controllers or methods.

public class IdCheck: ValidationAttribute
    {
        public string currentId { get; set; }

        public override bool IsValid(object value)
        {
            currentId = value as string;
            if (currentId != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

and I tried to use it like that:

[IdCheck(currentId = Session["UserId"])]
public class SomeController : Controller
{
//methods
}

However, I got an error with the message: "An object reference is required for the non static field, method or property 'Controller.Session'"

I can neither access the Session[] before a controller nor before method declaration. I have no idea how to instantiate or refere.

Is there a way to utilize Session[] in my case? Because I don't want to manually check each method with if statements like

if(Session["UserId"] != null) {}

Any alternative solution is more than welcomed.

Note: I am aware of that using Session is not a recommended way of implementing such a task. But my intention is to have an understanding of how login operations work before utilizing advanced Identity services.


Solution

  • Is there a way to utilize Session[] in my case?

    Not as you're doing now, but you could use HttpContext.Current.Session inside your custom attribute code instead of passing it as property.