我有这个过滤器类。
public class Sessional : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
LoggedUserInfo user = (LoggedUserInfo)session["User"];
if ((user == null && !session.IsNewSession) || (session.IsNewSession))
{
UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
string loginUrl = urlHelper.Content("~/Account/LogOut");
FAuth.AbandonSession();
FormsAuthentication.SignOut();
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
当我在Controller上应用它时,如果会话不可用,所有操作都将注销用户。 但我想编写属性,允许唯一的操作在没有登出的情况下完成其工作,例如UnSessional。
[Authorize]
[Sessional]
public class ReportController : Controller
{
[HttpGet]
[UnSessional]
public ActionResult GetReport() //unsessional action
{
return View();
}
[HttpPost]
public ActionResult GetReport(GetReportModel model) //sessional action
{
if (!ModelState.IsValid)
{
return View();
}
return View();
}
}
答案 0 :(得分:2)
您可以检查当前Action的“会话属性”是否存在,以下是示例代码:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(filterContext.ActionDescriptor.GetCustomAttributes(typeof(UnSessionAttribute), true).Length > 0)
{
return;
}
HttpSessionStateBase session = filterContext.HttpContext.Session;
LoggedUserInfo user = (LoggedUserInfo)session["User"];
if ((user == null && !session.IsNewSession) || (session.IsNewSession))
{
UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
string loginUrl = urlHelper.Content("~/Account/LogOut");
FAuth.AbandonSession();
FormsAuthentication.SignOut();
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}