public class AuthenAdminAttribute:FilterAttribute,IAuthorizationFilter
{ public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
//这个方法是在Action执行之后调用
} public void OnAuthorization(AuthorizationContext filterContext)
{
//这个方法是在Action执行之前调用
var user = filterContext.HttpContext.Session["userName"];
if (user == null)
{
//filterConetext.HttpContext.Response.Redirect("/Login/index");
var url = new UrlHelper(filterContext.RequestContext);
var urls = url.Action("Index", "Login");
filterContext.Result = new RedirectResult(urls);
}
}
}

  在需要使用做登录状态判断的地方添加[Autenadmin]放在类前面表示整个控制器的每个Action都需要验证

单独放在Action之前表示只有该Action需要验证

    [AuthenAdmin]
public class HelloController : Controller
{
// GET: Hello
public ActionResult Index()
{
return View();
}
public string welcome(string name,int id=1){ return HttpUtility.HtmlEncode("hello "+name+":"+id);
}
}
  • 在Controller类中方法访问级别为public的方法,就是行为(Action).
  • 如果不希望Controller类中的方法成为Action(可以在地址栏中被访问),有两种实现方式:
  1. 将方法的访问级别设置为private
  2. 在方法上添加特性标记[NonAction]

借鉴: http://www.lanhusoft.com/Article/73.html

方法二:
public class BaseController : Controller
{ protected override void OnActionExecuting(ActionExecutingContext filterContext)
{ if (HttpContext != null)
{
if (HttpContext.Session["userName"] != null)
{ }
else
{
filterContext.Result = new RedirectResult("/Login/Index");
}
}
base.OnActionExecuting(filterContext);
}
}

  

最新文章

  1. linux下命令行操作快捷键及技巧
  2. yii获取当前url和域名
  3. localstorage,sessionstorage使用
  4. u-boot启动流程分析(1)_平台相关部分
  5. CSS3 text-rendering属性
  6. Web.xml配置详解之context-param(转)
  7. asp.net读取文件
  8. php基础(三)超全局变量
  9. OpenGL---------光照的基本知识
  10. 通过日期在js中求出判断间隔天数,周期等实现分享
  11. .NET(C#)能开发出什么样的APP?盘点那些通过Smobiler开发的移动应用
  12. babel分析
  13. Qt: 非阻塞时间延迟;
  14. (3)打造简单OS-MBR引导区转移加载简单程序(突破512限制)
  15. Python-初识模块
  16. Latex: 保持参考文献大小写
  17. eclipse配置tomcat后出现:java virtual machine launcher Error:Could not ……,Program will exit.
  18. django配置Ueditor富文本编辑器
  19. C# 获取listview中选中一行的值
  20. js往div里添加table

热门文章

  1. UWP 协议启动
  2. (转) RabbitMQ学习之工作队列(java)
  3. Kafka学习笔记(6)----Kafka使用Producer发送消息
  4. FFmpeg avcodec_send_packet压缩包函数
  5. python实现定时发送消息
  6. Yii2.0 RESTful API 认证教程
  7. Python GitHub上星星数量最多的项目
  8. join()与os.path.join()的用法
  9. 【CodeForces 987C】Three displays
  10. 【codeforces 805C】Find Amir