Dan Hastings
Dan Hastings

Reputation: 3280

ASP.NET Access controller properties from AuthorizeAttribute method

I have created a base controller for an API using an MVC 4 project. Everything works as I want, but in the interests of efficiency, I want to be able to access some of the custom properties from my base controller from the OnAuthorization method. I need to perform some SQL queries to make sure the access token is valid and so on. Id rather make this query once and store the object as a property on the controller so that i can access it later without needing to do a query again.

In short, this is what i want to do.

[APIActionFilter]
public class APIBaseController : ApiController
{
    public APIClient client;
    public class APIActionFilter : System.Web.Http.AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext filterContext)
        {
            //get data from the database. 
            Controller.client = objectmadefromdb;
        }
    }
}

There must be a reference to this object passed somewhere?

Upvotes: 3

Views: 1655

Answers (1)

Dan Hastings
Dan Hastings

Reputation: 3280

The first comment was along the lines, but was not correct. I was able to get this working using the following

public override void OnAuthorization(HttpActionContext filterContext)
{
    var controllerRef = filterContext.ControllerContext.Controller as APIBaseController;
    controllerRef.userdata = new user("123");
}

I was now able to access the properties from the main controller. I was able to set some public properties on the APIBaseController object and directly assign values to them. Could of course use getters and setters or whatever.

To confirm it works i was able to create a new controller that inherited the base controller. From any action within that controller I was able to access the properties of the APIBaseController object and they were populated with the data i set in the OnAuthorization method.

Upvotes: 4

Related Questions