C# MVC登录判断状态
2024-09-01 16:16:49
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(可以在地址栏中被访问),有两种实现方式:
- 将方法的访问级别设置为private
- 在方法上添加特性标记[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);
}
}
最新文章
- linux下命令行操作快捷键及技巧
- yii获取当前url和域名
- localstorage,sessionstorage使用
- u-boot启动流程分析(1)_平台相关部分
- CSS3 text-rendering属性
- Web.xml配置详解之context-param(转)
- asp.net读取文件
- php基础(三)超全局变量
- OpenGL---------光照的基本知识
- 通过日期在js中求出判断间隔天数,周期等实现分享
- .NET(C#)能开发出什么样的APP?盘点那些通过Smobiler开发的移动应用
- babel分析
- Qt: 非阻塞时间延迟;
- (3)打造简单OS-MBR引导区转移加载简单程序(突破512限制)
- Python-初识模块
- Latex: 保持参考文献大小写
- eclipse配置tomcat后出现:java virtual machine launcher Error:Could not ……,Program will exit.
- django配置Ueditor富文本编辑器
- C# 获取listview中选中一行的值
- js往div里添加table
热门文章
- UWP 协议启动
- (转) RabbitMQ学习之工作队列(java)
- Kafka学习笔记(6)----Kafka使用Producer发送消息
- FFmpeg avcodec_send_packet压缩包函数
- python实现定时发送消息
- Yii2.0 RESTful API 认证教程
- Python GitHub上星星数量最多的项目
- join()与os.path.join()的用法
- 【CodeForces 987C】Three displays
- 【codeforces 805C】Find Amir