[英]c# mvc3 controller having a overall if-statement
im new to c# but what im trying to do instead of having a if-statement in every actionresult. 我是C#的新手,但是我想做些什么,而不是在每个操作结果中都包含if语句。
can i have a overall if-statement for the controller and just run that for every actionresult? 我可以为控制器提供一个整体的if语句,并为每个操作结果运行它吗?
public InformationController {
if (Session["CharacterName"] == null)
{
return RedirectToAction("logon", "Auth");
}
something like that? 这样的东西?
我将为此实现IRouteConstraint来创建一个类,并以此构建路由。
Create a ActionFilterAttribute
like this: 创建一个这样的
ActionFilterAttribute
:
public class MyFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//your logic here
}
}
and apply this attribute to your controller 并将此属性应用于您的控制器
[MyFilter]
public class MyController : Controller
This looks like a prime candidate for an Action Filter . 这看起来像是Action Filter的主要候选对象。 Something like this:
像这样:
public class CheckSessionCharacterNameAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Session["CharacterName"] == null)
{
filterContext.Result = new RedirectToRouteResult(...);
}
}
}
对于ASP.Net MVC框架,我更喜欢实现ActionFilterAttribute类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.