本文介绍了检查会话控制器在mvc 4中初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi
我想在控制器初始化方法上检查SESSION。



我的代码是



protected override void Initialize(RequestContext requestContext = null)

{



try

{

UserSession _UserSession =(UserSession)Session [user];

if(_UserSession.MemberID == 0)

{



RedirectToAction(登录,帐户);

}

}

catch

{

RedirectToAction(登录,帐户);

}



//requestContext.RouteData = RedirectToAction(LogIn,Account);



}



但是错误



对象重新ference不设置为对象的实例。

描述:在执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。



异常详细信息:System.NullReferenceException:对象引用未设置为实例一个对象。



如果我添加

base.Initialize(requestContext);

没有错误,但没有检查会话值。

如何解决此问题。

hiI want to check SESSION on controller Initialize method.

my code is

protected override void Initialize(RequestContext requestContext = null)
{

try
{
UserSession _UserSession = (UserSession)Session["user"];
if (_UserSession.MemberID == 0)
{

RedirectToAction("LogIn", "Account");
}
}
catch
{
RedirectToAction("LogIn", "Account");
}

//requestContext.RouteData = RedirectToAction("LogIn", "Account");

}

but through an error

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

If i add
base.Initialize(requestContext);
No Error,but not check session value.
how to solve this.

推荐答案

protected override void OnException(ExceptionContext filterContext)
{
    if (filterContext.Exception is UnauthorizedAccessException)
    {
        //
        // Manage the Unauthorized Access exceptions
        // by redirecting the user to Home page.
        //
        filterContext.ExceptionHandled = true;
        filterContext.Result = RedirectToAction("LogIn", "Account");
    }
    //
    base.OnException(filterContext);
}





2.如果您想在执行当前操作之前控制控制器操作,您可以执行通过覆盖下一个控制器成员:





2.If you want to have control over the controller action before to execute the current action, you could do it by overriding the next controller members:

/// <summary>
        /// Disable the Async support.
        /// </summary>
        /// <remarks>
        /// Must be disable, otherwise ExecuteCore() will not be invoked in MVC4 like was in MVC3!
        /// </remarks>
        protected override bool DisableAsyncSupport
        {
            get { return true; }
        }

protected override void ExecuteCore()
        {
            
//
// Your code for accessing the data from Session 
//
//...

            //
            // Invokes the action in the current controller context.
            //
            base.ExecuteCore();
        }


这篇关于检查会话控制器在mvc 4中初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 23:46