C# 控制器函数上方的自定义属性
我想把C# 控制器函数上方的自定义属性,c#,asp.net-mvc-4,custom-attributes,C#,Asp.net Mvc 4,Custom Attributes,我想把[FirstTime]属性放在控制器函数之上,然后创建一个FirstTimeAttribute,它有一些逻辑来检查用户是否输入了他的名字,如果没有,则将他重定向到/Home/FirstTime 因此,不要这样做: public ActionResult Index() { // Some major logic here if (...) return RedirectToAction("FirstTime", "Home"); return Vi
[FirstTime]
属性放在控制器函数之上,然后创建一个FirstTimeAttribute
,它有一些逻辑来检查用户是否输入了他的名字,如果没有,则将他重定向到/Home/FirstTime
因此,不要这样做:
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]属性属性代码:
public class FirstTimeAttribute : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (string.IsNullOrEmpty(filterContext.HttpContext.Request[name]))
{
filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary
{
{ "controller", "Home" },
{ "action", "FirstTime" },
{ "area", string.Empty }
});
}
}
}
用法:
[FirstTime]
public ActionResult Index(string name)
{
return View();
}
实现IActionFilter是多余的。ActionFilterAttribute已经实现了这个接口,您的FirstTimeAttribute继承自ActionFilterAttribute:)太棒了,非常感谢。在添加了
filterContext.Result=new RedirectResult(…)后,工作非常出色代码>。。。非常感谢。很高兴我能帮忙。很抱歉没有在一开始就添加这一点;我忘了(做别的事情)