2

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?

Dan Hastings
  • 3,241
  • 7
  • 34
  • 71
  • check `filterContext.ControllerDescriptor` – Nkosi Feb 07 '17 at 14:07
  • Not sure how helpful it'll be, but I did something similar with making a database call in a custom authorize attribute. See here: [SO link](http://stackoverflow.com/questions/29172150/custom-webapi-authorization-database-call) – MisterIsaak Feb 07 '17 at 14:10

1 Answers1

4

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.

Dan Hastings
  • 3,241
  • 7
  • 34
  • 71
  • Could you please let me know that how to achieve the same functionality in .net6? Since now OnAuthorization method is taking parameter of type AuthorizationFilterContext. – Alii Sep 12 '22 at 09:43