英文:
Why is this value in my Base class property wrong?
问题
I have a BaseController that all of my Controllers derive from.
public class BaseApiController : ApiController
{
public static User CurrentUser;
public BaseApiController()
{
}
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
var request = controllerContext.Request;
if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme.Equals("bearer", StringComparison.OrdinalIgnoreCase))
{
CurrentUser = Helpers.JwtAuthentication.UserToken(request.Headers.Authorization.Parameter);
}
}
protected User ActiveUser
{
get
{
return CurrentUser;
}
}
}
I make use of the ActiveUser.Id
object throughout many of my controllers. Thousands of users use the system.
Our logs indicate that the incorrect user is being associated with actions they didn't perform.
Why might the ActiveUser property be incorrect?
英文:
I have a BaseController that all of my Controllers derive from.
public class BaseApiController : ApiController
{
public static User CurrentUser;
public BaseApiController()
{
}
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
var request = controllerContext.Request;
if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme.Equals("bearer", StringComparison.OrdinalIgnoreCase))
{
CurrentUser = Helpers.JwtAuthentication.UserToken(request.Headers.Authorization.Parameter);
}
}
protected User ActiveUser
{
get
{
return CurrentUser;
}
}
}
I make use of the ActiveUser.Id
object through out a lot of my controllers. There are thousands of users making use of the system.
Our logs are showing us that the incorrect user is being saved against logs they did not perform.
Why would the ActiveUser property be incorrect?
答案1
得分: 4
因为CurrentUser被声明为静态的。这意味着该值在所有具有BaseApiController类型的对象之间共享。在asp.net中,每个请求都由一个单独的线程和一个单独的对象处理,但由于它们都共享相同的CurrentUser变量,因此该值将是最后一个运行Initialize方法的请求所设置的值。因此,CurrentUser会在请求之间泄漏。
英文:
It's because CurrentUser is declared static. That means the value is shared between all the objects that have the BaseApiController type. In asp.net each request is processed on a separate thread by a separate object, however because they all share the same CurrentUser variable the value will be whatever the last request to run Initialize set it to. Thus the CurrentUser will leak across requests.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论