Using the Action Global filter in MVC appears: The Web page does not work correctly and redirects you too many times. Solutions

Source: Internet
Author: User
Tags httpcontext

When we visit a website, we need to detect if the user is logged in (via session is null). We know that in WebForm you can define a BasePage class that allows him to inherit System.Web.UI.Page, rewrite its oninit () method, and in OnInit () determine if there is a user login information in the session.

/// <summary>    ///Public base classes do some public things./// </summary>     Public classBasePage:System.Web.UI.Page {//the OnInit () method corresponding to the page life-cycle init event//This method is performed before the Pageload method//Override means overriding the OnInit method OnInit method, which is raised after all controls have been initialized and all skin settings have been applied. Use this event to read or initialize the properties of a control        protected Override voidOnInit (EventArgs e) {Base.            OnInit (e); if(session["UserInfo"] ==NULL)//Check if the user is logged in            {                   //Jump to login page            }        }    }

How do you check it under MVC?

We know that under MVC you can customize an attribute class to [attribute] on a controller or a controller, where only the Actionfilter filter is required (the action method executes before and after execution), and MVC provides the Iactionfilter interface. (For convenience we can use Microsoft to provide good ActionFilterAttribute class, he is the filter attribute of the base class, is also an abstract class, in fact, this abstract class implementation of Iactionfilter and Iresultfilter)

Definition of the Iactionfilter interface:

   // called after the action method is executed.         void onactionexecuted (ActionExecutedContext filtercontext);                  // called before the action method is executed.              void

Create a new attribute class Logincheckfilterattribute, let him inherit the ActionFilterAttribute, and rewrite the OnActionExecuting method in which to complete the checksum

 Public classLogincheckfilterattribute:actionfilterattribute {//indicates whether to check login         Public BOOLIscheck {Get;Set; } //execute this method before the action method executes         Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {Base.            OnActionExecuting (Filtercontext); if(Ischeck) {//Verify that the user is logged on                if(filtercontext.httpcontext.session["Loginuser"] ==NULL)                {                    //Jump to landing pageFilterContext.HttpContext.Response.Redirect ("/userlogin/index"); }            }        }    }

How do you make this filter work?

Step: 1, register the global filter for the MVC program in the Global.asax file, call Filterconfig.registerglobalfilters (globalfilters.filters). The Filterconfig class is in the App_start folder (the creation of a new MVC project is automatically generated), and in the static method of filterconfig, public static void Registerglobalfilters ( Globalfiltercollection filters) Register Global filters

 Public class Filterconfig    {        // This method is used to register a global filter (called in global)         Public Static void registerglobalfilters (globalfiltercollection filters)        {            //filters. ADD (New Handleerrorattribute ());            Filters. ADD (newtrue  });        }    }

Note To assign a value of true to the Ischeck property of an attribute class instance, the session check does not work.

In this way, the Logincheckfilterattribute feature will work for the Controller and action in the entire MVC program, meaning that the override onactionexecuting method in the attribute class is called before the action method is executed. This allows users to visit the site will first detect whether the user is logged in, if not logged in will jump to the login page.

But! But! The problem is, because we are registering a global filter, this filter feature will work on all the actions of the controller, when visiting the website (for example, we register the default route to/home/index) will first jump to/home/index, then do not execute the Index method , the check in OnActionExecuting () is performed first, and the session is Null,response.redirect ("/userlogin/index") to the login page, and we still don't see the login page in the browser. Why is it? Remember that we registered the global filter, the action object including all the controller under the action of course also includes/userlogin/index, the code went here will again execute onactionexecuting () method, found session["UserInfo" ==]null, jumped to the login page, we can't even see the login page can not enter the user name password session will not have login information, the browser will return "This page contains redirect Loop" error page, that is, will continue to redirect to the login page, like a dead loop, The browser certainly strikes.

How to solve this bug?

Workaround: Make the Userlogincontroller controller feature

false)]  // The user login check feature (Ischeck set to False does not make it work on this controller, but on other controllers and action to prevent redirection loops)     Public class Userlogincontroller:controller    {...     }

When defining this attribute class, we have a bool attribute Ischeck, which indicates whether the checksum is set to false to indicate no checksum. By the way, Logincheckfilterattribute can omit the attrbute suffix.

Be sure to hit this feature on the controller, not just for one of the actions below, because there is an action to generate the CAPTCHA and the action to process the login request, they do not need a session check (meaningless), Hitting the feature on the controller will work on all the actions underneath it, without hitting the feature for each action, saving the amount of code. We have registered a global filter and individually filter the Userlogincontroller controller, there is a priority problem action>controller> the global, Userlogincontroller are not affected by global filters. Test here, enter the website address, successfully entered the login page. Problem solving.

This article mainly refers to: http://www.cnblogs.com/Look_Sun/p/4425083.html this article. When I encountered this problem, I read this article and the problem I encountered during development is basically the same. But the friend wrote the global filter seems to have a problem, just want to judge session["UserInfo"]==null when you can, he session["UserInfo"]!=null when also made a judgment, and did jump to. All when the click Landing, redirected to the/home/index, but to the Home will be a dead loop.

A very good view of the filter in MVC: Http://pan.baidu.com/s/1i5zwhjZ reply I want the password to discuss the problem together

Using the Action Global filter in MVC appears: The Web page does not work correctly and redirects you too many times. Solutions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.