本文介绍了ASP.NET MVC:不在重定向时执行 actionfilters 并抛出 HttpException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 OnActionExecuted 过滤器,用来自 db 的数据填充一些视图模型属性(我没有使用 ViewData["somekey"],更喜欢从共同祖先继承的许多 ViewModel).

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

问题在于,当一个动作导致重定向或404错误时,OnActionExecuted会尝试访问尚未初始化的ViewModel.此外,填充这些值完全没有用,因为它们不会被使用,因为将调用另一个操作.

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?

推荐答案

一个简单的解决方案是在模型不存在时不填写它:

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

这篇关于ASP.NET MVC:不在重定向时执行 actionfilters 并抛出 HttpException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:26