【发布时间】:2016-08-31 19:42:09
【问题描述】:
我目前在我的 MVC 项目中有以下 ActionFilterAttribute。它适用于第一个请求,但后续请求会返回 DbContext 已释放的消息。
public class PermissionFilter : ActionFilterAttribute
{
private readonly ApplicationGroupManager _groupManager = new ApplicationGroupManager();
private readonly ActionPermissionManager _permissionManager = new ActionPermissionManager();
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
if (request.IsAjaxRequest())
{
#region Preventing caching of ajax request in IE browser
response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
response.Cache.SetValidUntilExpires(false);
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.Cache.SetNoStore();
#endregion Preventing caching of ajax request in IE browser
}
var currentAreaName = filterContext.RequestContext.RouteData.DataTokens["area"];
var currentActionName = filterContext.ActionDescriptor.ActionName;
var currentControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var userId = HttpContext.Current.User.Identity.GetUserId<int>();
if (!_groupManager.UserHasAdministratorAccess(userId))
{
if (!_permissionManager.HasPermission((currentAreaName == null ? String.Empty : currentAreaName.ToString()), currentControllerName, currentActionName, userId))
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Account" }, { "action", "Login" } });
}
}
base.OnActionExecuting(filterContext);
}
}
我已经阅读了足够多的内容,意识到这是 MVC3 中引入的以下更改的问题
重大更改:在以前版本的 ASP.NET MVC 中,操作过滤器 除少数情况外,按请求创建。这种行为从来没有 一个有保证的行为,但仅仅是一个实现细节和 过滤器的合同是认为它们是无国籍的。在 ASP.NET MVC 3 中, 过滤器被更积极地缓存。因此,任何自定义操作 不正确地存储实例状态的过滤器可能会被破坏。
我不确定如何最好地解决此问题。我考虑将我的两个私有只读字段移动到 OnActionExecuting 部分,我相信这可以解决问题,但我担心多线程以及该实现是否存在问题。
似乎很多人使用 Castle Windsor 或 Ninject 解决了这个问题,但这些超出了我的专业水平,即使在完成了 Windsor 教程 (https://github.com/castleproject/Windsor/blob/master/docs/mvc-tutorial-intro.md) 之后,我也无法理解我到底需要做什么.
【问题讨论】:
-
在您的情况下,使用 Castle Windsor 或 Ninject 就像试图用雷神之锤敲击别针。
标签: c# asp.net asp.net-mvc dbcontext actionfilterattribute