通过继承ActionFilterAttribute使用其中的OnActionExecuting方法来实现IActionFilter接口。
派生ActionFilterAttribute类
// 登录认证特性
public class AuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["username"] == null)
filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } });
base.OnActionExecuting(filterContext);
}
}
使用方法
public class HomeController : Controller
{
[Authentication]
public ActionResult Index()
{
return View();
}
}
针对整个MVC项目的所有Action都使用过滤器,则需要如下操作
1. 确保Global.asax.cs的Application_Start方法中包含FilterConfig被调用
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
2. 在FilterConfig.cs文件中注册相应的特性过滤器
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthenticationAttribute());
}
}
本文介绍如何在ASP.NET MVC应用中实现登录认证过滤器。通过创建自定义的AuthenticationAttribute类继承ActionFilterAttribute,并覆盖OnActionExecuting方法来检查用户会话状态。如果未登录则重定向到登录页面。此外,还介绍了如何在整个项目中全局注册此类过滤器。
957

被折叠的 条评论
为什么被折叠?



