C# 如果我将构造函数添加到authorized属性的扩展中,会在每个附加了该属性的请求上调用该构造函数吗?
我已经编写了System.Web.Mvc属性的自定义扩展。此处的Microsoft引用: 此扩展将覆盖AuthorizeAttribute中的AuthorizeCore功能,其预期用途是此自定义属性将保留AuthorizeAttribute的现有功能,但如果配置设置为true,则还将对用户会话执行附加检查 我们担心性能,因为此自定义属性将附加到每个API请求,取代当前使用的Authorize属性。目前,在AuthorizeCore函数中,我们正在读取每个请求的配置设置,并想知道是否有更好的方法来完成这些操作 那么,如果我为我的自定义属性创建一个构造函数,读取那里的配置,然后将其存储在一个静态变量中,有人知道这个构造函数是否会在每个附加了这个自定义属性的请求中被调用,或者只调用一次,然后,在发出请求时调用的每个AuthorizeCore调用都可以引用存储已从配置中读取的值的静态变量C# 如果我将构造函数添加到authorized属性的扩展中,会在每个附加了该属性的请求上调用该构造函数吗?,c#,security,authorize,system.web,C#,Security,Authorize,System.web,我已经编写了System.Web.Mvc属性的自定义扩展。此处的Microsoft引用: 此扩展将覆盖AuthorizeAttribute中的AuthorizeCore功能,其预期用途是此自定义属性将保留AuthorizeAttribute的现有功能,但如果配置设置为true,则还将对用户会话执行附加检查 我们担心性能,因为此自定义属性将附加到每个API请求,取代当前使用的Authorize属性。目前,在AuthorizeCore函数中,我们正在读取每个请求的配置设置,并想知道是否有更好的方法来
你不需要构造函数。您只需要添加一个静态类bool?可为空的布尔变量。然后,在方法中,如果变量为null,则仅从config读取数据。在下一次执行中,由于它不是null,所以它不读取config 公共类AuthorizeSessionAttribute:AuthorizeAttribute { 专用静态bool?\u管理会话
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)
{
if (!_manageSession.HasValue && bool.TryParse(ConfigurationManager.AppSettings["ManageSession"], out bool parsedSetting))
{
_manageSession = parsedSetting;
}
if (_manageSession)
{
// custom logic goes here
}
}
return isAuthorized;
}
}这可能是最好的建议。我刚刚尝试添加一个构造函数作为自定义属性,是的,为了回答我自己的问题,每个附加了自定义属性的API请求都会调用这个构造函数。您的建议将取代对每个请求调用Configuration.AppSettings和bool.TryParse,而只是对每个请求进行空检查。我觉得比较便宜,所以我就买了。
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)
{
if (!_manageSession.HasValue && bool.TryParse(ConfigurationManager.AppSettings["ManageSession"], out bool parsedSetting))
{
_manageSession = parsedSetting;
}
if (_manageSession)
{
// custom logic goes here
}
}
return isAuthorized;
}