ASP.NET MVC:不执行actionfilters的重定向和抛出HttpException
我创建了一个OnActionExecuted过滤器来填充一些viewmodel属性与数据从数据库(我没有使用ViewData [“somekey”],喜欢许多ViewModels降序一个共同的祖先)。ASP.NET MVC:不执行actionfilters的重定向和抛出HttpException
public class BaseController : Controller {
protected DataClassesDataContext context = new DataClassesDataContext();
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
ViewModel model = (ViewModel) ViewData.Model;
model.IsUserAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated;
if (model.IsUserAuthenticated)
{
model.UserName = filterContext.HttpContext.User.Identity.Name;
}
model.CommonAttribute = from c in context.Something select new SomethingElse() {...};
}
}
的问题是,当在一个重定向的动作的结果或404错误,OnActionExecuted试图访问视图模型,其尚未被初始化。而且,填充这些值完全没用,因为它们不会被使用,因为另一个动作将被调用。
如何避免在重定向上填充viewodel?
回答:
一个平凡的解决办法是在模型中不填的时候它不存在:
ViewModel model = ViewData.Model as ViewModel; if (model != null)
{
model.IsUserAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated;
if (model.IsUserAuthenticated)
{
model.UserName = filterContext.HttpContext.User.Identity.Name;
}
model.CommonAttribute = from c in context.Something select new SomethingElse() {...};
}
以上是 ASP.NET MVC:不执行actionfilters的重定向和抛出HttpException 的全部内容, 来源链接: utcz.com/qa/265690.html