多语言展示
当前在线:1367今日阅读:23今日分享:25

C# MVC 使用Attribute做站点保护

在MVC编程中经常会遇到只有登录后才能访问内部的功能页面,如果直接访问就提示未登录或直接跳转到登录页面,这时候可以使用AuthorizeAttribute来实现。
工具/原料

VS2013 MVC

方法/步骤
1

首先自定义类CustomAttribute 继承 AuthorizeAttribute。 public class CustomAttribute : AuthorizeAttribute    {        public override void OnAuthorization(AuthorizationContext filterContext)        {            var userSession = filterContext.HttpContext.Session['UserMsg'];            if(filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute),true))            {                //action有AllowAnonymous属性                return;            }            else if (filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))            {                //Controller有AllowAnonymous属性                return;            }             else if (userSession == null )//增加session值判断            {                filterContext.HttpContext.Response.Redirect('/Home/Login');            }            else            {                return;            }        }    }

2

在需要保护的Action或Controller上面添加属性。    [CustomAttribute]    public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        [AllowAnonymous]//该属性可以让action不去做验证        public ActionResult Login()        {            return View();        }     }

注意事项

如果不需要做保护的页面,如登录页可以加上AllowAnonymous属性。

推荐信息