2

我的应用程序中有一个自定义 AuthorizeAttribute ,它带有一个输入参数bool UserIsOnline。此参数用于增加一个表字段,该字段包含有关上次用户交互时间的信息,即对于在幕后执行的 ajax 请求,我提供一个值false,对于常规请求或用户发起的 ajax 请求,一个true值。

这在大多数情况下都有效,但并非总是如此。我读过这 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;
  }
}
4

1 回答 1

1

您可以完全跳过参数并使用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
    }
于 2012-09-21T20:07:17.500 回答