asp.net-mvc – 从控制器重定向初始化不工作

我有覆盖控制器,检查是否存在某些会话数据.这些数据是存储库正常工作所必需的,如果它不存在,那么在检查用户应该注销后.
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    if (Session["CompanyID"] != null)
    {
        repo.CompanyID = (long)Session["CompanyID"];
    }
    else
    {
        RedirectToAction("logoff","Account");
    }
}

我的代码看起来像这样,但即使调用RedirectToAction,控制器仍然会打开认操作,用户不会注销.
你可以建议如何处理这个问题吗?

我以这种方式使用这个会话数据,因为这是我可以得到的第一个,我知道,在这里我可以检查这个特定的数据是否存在.当用户登录时写入.

此数据是用户数据库中的一部分.我已经制定了一个定制的会员和角色提供者.有没有办法将此数据添加到MembershipUser类型的“用户”,因此可以在构造函数中访问用户名

解决方法

考虑使用自定义 ActionFilter.
public class HasCompanyIdAttribute : ActionFilterattribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["CompanyID"] == null)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {action = "logoff",controller = "Account"}));
        }
    }
}

它可以如此应用:

[HasCompanyId]
public class MyController : Controller 
{
    public ActionResult SomeAction()
    {
        return View();
    }
}

这将应用MyController(或它的子类)处理的所有请求的属性.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....