如果临时数据在每个控制器中都有值,如何检查条件

时间:2016-05-17 05:08:16

标签: asp.net-mvc optimization

我正在寻找优化的方法来检查tempdata是否在MVC的每个控制器中都有值。我不想在每个控制器中写入,在哪里可以编写这样的条件:如果临时数据有值,则显示视图,否则重定向到登录页面。

3 个答案:

答案 0 :(得分:1)

  1. 请创建一个基本控制器

    public class BaseController : Controller
    {
    protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
    {
        var id = filterContext.Controller.TempData["id"];
        if (id == null)
        {
            filterContext.Result = RedirectToAction("Index", "Home");
        }
        base.OnActionExecuting(filterContext);
      }
     }
    
  2. 之后你必须在非常控制器上继承基本控制器。

    public class CheckController : BaseController
    {
      public ActionResult Index()
      {
        TempData["id"] = 2;
    
        return View();
       }
      }
    

答案 1 :(得分:0)

在每个控制器中使用基本控制器。然后检查基本控制器,如果临时数据有值,则显示视图,否则重定向到登录页面。

答案 2 :(得分:0)

过滤代码:

public class MyCustomAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.TempData.Add("some key", "some value");
    }
}

行动代码:

[MyCustom]
public ViewResult Index()
{
    string value = TempData["key"] as string;
    return View();
}
相关问题