简体   繁体   English

如何检查控制器的每个动作的会话?

[英]How to check sessions on every action of a controller?

i have a controller called AllEntities it has multiple actions like GetEntityByTypeId and GetLastEntity 我有一个名为AllEntities的控制器,它具有多个操作,例如GetEntityByTypeIdGetLastEntity

i want to do a session check whenever AllEntities controller is used 每当使用AllEntities控制器时,我都想进行会话检查

like suppose i request a url http://localhost:59656/AllEntities/GetLastEntity 像假设我请求一个URL http://localhost:59656/AllEntities/GetLastEntity
then it should check weather session is assigned or not 然后应该检查是否分配了天气会话

one way of doing this would be put condition if (Session["userName"] == null) if (Session["userName"] == null)放置条件
in every Action of this controller 在此控制器的每个动作中
How can it be checked once for entire AllEntities controller 如何对整个AllEntities控制器进行一次检查

any kind of help would be appreciated 任何形式的帮助将不胜感激

You could override the controllers Initialize method which would fire on every action. 您可以覆盖控制器的Initialize方法,该方法将在每次操作时触发。 I use it to populate ViewBag elements I need on multiple/all views. 我用它来填充多个视图/所有视图上所需的ViewBag元素。

public class YourController : Controller
{

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);

        try
        {
            //do your session check here...

            //alternatively, if you wanted to limit to certain actions in your controller you could say: 
            var actionName = requestContext.RouteData.Values["action"].ToString().ToLower();
            if(actionName == "actionName" || actionName == "actionName2") {
               //do your limited session work...
            }
        }
        catch (Exception e) { }

    }
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在每个控制器动作中使用异步ViewModel? - How to use asynchronous ViewModel in every controller action? 对每个页面请求执行检查(不是每个控制器操作) - Execute check on each page request (not every controller action) 如何避免重复为控制器中的每个操作发生的代码 - How to avoid duplicating code that occurs for every action in a controller 在每个控制器操作之前/之后执行代码 - Execute code before/after every controller action 如何查看ASP.Net MVC中调用的每个控制器和操作方法? - How to see every controller & action method called in ASP.Net MVC? 检查操作 controller 中的授权策略 - Check authorization policy inside the action controller 自定义 MVC controller 动作属性来检查和操作动作输入 - Custom MVC controller action attribute to check and manipulate action inputs 如何在 ASP NET Core 3.1 中的任何 controller 的每种方法中检查/重定向? - How to check/redirect in every method of any controller in ASP NET Core 3.1? 如何检查控制器上下文是否是ASP.NET Core MVC中的子操作? - How to check if controller context is child action in ASP.NET Core MVC? 如何检查 controller 和/或操作是否作为来自中间件的有效端点存在? - How do I check if a controller and / or action exists as a valid endpoint from a middleware?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM