I have written a custom extension of the the System.Web.Mvc AuthorizeAttribute
.
The Microsoft Reference here : SystemWebMvcAuthorizeAttribute.
This extension overrides the AuthorizeCore
function from AuthorizeAttribute
, and the intended use is that this custom attribute will retain the existing functionality of AuthorizeAttribute
, but also perform an additional check on the user's session if a config
setting is set to true.
We are worried about performance since this custom attribute will be attached to every API request, replacing the currently used Authorize
attribute. Currently, in the AuthorizeCore
function, we are reading the config
setting on every single request, and are wondering if there is a better way of doing things.
So, if I create a constructor for my custom attribute, read the config
there, and then store it in a static
variable, does anyone know if this constructor will be called on every single request made which has this custom attribute attached, or just once, and then every call to AuthorizeCore
(invoked when a request is made) can refer to the static
variable storing the value that has already been read from the config
?
public class AuthorizeSessionAttribute : AuthorizeAttribute
{
bool _manageSession = false;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// Since we are overriding the AuthorizeCore from AuthorizeAttribute, make sure to call the base method first to check that this request 'isAuthorized' before proceeding.
bool isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
// Any way to improve this?
bool.TryParse(ConfigurationManager.AppSettings["ManageSession"], out _manageSession);
if (_manageSession)
{
// custom logic goes here
}
}
return isAuthorized;
}
}