ASP.NET MVC: Not executing actionfilters on redirect and throw HttpException

爷,独闯天下 提交于 2019-12-24 19:18:42

问题


I've created an OnActionExecuted filter to populate some viewmodel attributes with data from db (I'm not using ViewData["somekey"], preferring many ViewModels descending from a common ancestor).

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() {...};
    }
}

The problem is that when an action results in a redirect or a 404 error, OnActionExecuted tries to access ViewModel, which has not been initialized. Also, it's completely useless to fill those values, as they will not be used, since another action is going to be called.

How can I avoid filling viewodel on redirect?


回答1:


A trivial solution would be to not fill in the model when it doesn't exist:

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() {...};
}


来源:https://stackoverflow.com/questions/1347365/asp-net-mvc-not-executing-actionfilters-on-redirect-and-throw-httpexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!