控制器功能上方的自定义属性 [英] Custom Attribute above a controller function

查看:87
本文介绍了控制器功能上方的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将[FirstTime]属性放在控制器函数上方,然后创建一个FirstTimeAttribute,该FirstTimeAttribute具有一些逻辑,可以检查用户是否输入了他的名字,如果没有输入,将其重定向到/Home/FirstTime./p>

所以不要这样做:

public ActionResult Index()
{
    // Some major logic here
    if (...)
        return RedirectToAction("FirstTime", "Home");

    return View();
}

我会这样做:

[FirstTime]
public ActionResult Index()
{
    return View();
}

这可能吗?

解决方案

好的.做类似

public class FirstTimeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Session != null)
        {
          var user = filterContext.HttpContext.Session["User"] as User;
          if(user != null && string.IsNullOrEmpty(user.FirstName))
              filterContext.Result = new RedirectResult("/home/firstname");
          else
          {
              //what ever you want, or nothing at all
          }
         }
    }
}

只需在您的操作中使用 [FirstTime] 属性

I want to put [FirstTime] attribute above a controller function and then create a FirstTimeAttribute that has some logic that checks whether the user has entered his name, and redirects him to /Home/FirstTime if he hasn't.

So Instead of doing:

public ActionResult Index()
{
    // Some major logic here
    if (...)
        return RedirectToAction("FirstTime", "Home");

    return View();
}

I would just do:

[FirstTime]
public ActionResult Index()
{
    return View();
}

Is this possible?

解决方案

Sure. Do something like

public class FirstTimeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Session != null)
        {
          var user = filterContext.HttpContext.Session["User"] as User;
          if(user != null && string.IsNullOrEmpty(user.FirstName))
              filterContext.Result = new RedirectResult("/home/firstname");
          else
          {
              //what ever you want, or nothing at all
          }
         }
    }
}

And just use [FirstTime] attribute on your actions

这篇关于控制器功能上方的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆