我的应用程序中有一个自定义的 AuthorizeAttribute,它接受一个输入参数 bool UserIsOnline
。此参数用于增加一个表字段,该字段包含有关上次用户交互时间的信息,即对于在后台执行的 ajax 请求,我提供一个 false
,对于常规请求或用户发起的请求ajax 请求,一个 true
值。
这在大多数情况下都有效,但并非总是如此。 I've read that AuthorizeAttribute
不是线程安全的,这让我想知道这个 UserIsOnline
参数是否错误,因为它在被处理之前被另一个进程修改了。我将如何解决这个问题?我不应该为此操作使用 AuthorizeAttribute 吗?
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private MyMembershipProvider _provider = new MyMembershipProvider(); // this class is thread-safe
private bool _userIsOnline = true;
public bool UserIsOnline { get { return _userIsOnline; } set { _userIsOnline = value; } }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
// Check if user is authenticated
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
// Check that the user still exists in database
MyMembershipUser myUser = (MyMembershipUser)_provider.GetUser(user.Identity.Name, _userIsOnline);
if (myUser == null)
{
// User does not exist anymore, remove browser cookie
System.Web.Security.FormsAuthentication.SignOut();
return false;
}
return true;
}
}
最佳答案
您可以完全跳过参数并使用 httpContext.Request.IsAjaxRequest
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
// Check if user is authenticated
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
if (!httpContext.Request.IsAjaxRequest())
{
// do your thing in the DB
}
关于c# - AuthorizeAttribute 和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12194459/