In MVC, the Action Global filter is used: the webpage cannot operate normally and you are redirected too many times. Solution: mvcaction

Source: Internet
Author: User

In MVC, the Action Global filter is used: the webpage cannot operate normally and you are redirected too many times. Solution: mvcaction

PrefaceWhen we access a website, we need to check whether the user has logged on (whether the Session is null). We know that a BasePage class can be defined in WebForm to inherit the System. web. UI. page, override its OnInit () method, and judge whether the Session has user login information in OnInit.

/// <Summary> /// perform some common tasks in the public base class /// </summary> public class BasePage: System. web. UI. page {// OnInit () method corresponding to the Page Life Cycle Init event // This method will be executed before the PageLoad method // override indicates rewriting the OnInit method, triggered after all controls have been initialized and all appearance settings have been applied. Use this event to read or initialize the control property protected override void OnInit (EventArgs e) {base. onInit (e); if (Session ["UserInfo"] = null) // check whether the user is logged on {// jump to the logon page }}}

In mvc, how can I verify the data?

We know that in MVC, you can customize the feature class to add [features] to the Action in the Controller or controller. Here, you only need the ActionFilter (which is executed before and after the Action method is executed). MVC provides the IActionFilter interface. (For convenience, we can use the ActionFilterAttribute class provided by Microsoft. It is the base class of the filter feature and an abstract class. In fact, this abstract class implements IActionFilter and IResultFilter)

IActionFilter interface definition:

// Call the operation method after execution. Void OnActionExecuted (ActionExecutedContext filterContext); // call before executing the operation method. Void OnActionExecuting (ActionExecutingContext filterContext );

Create a new feature class LoginCheckFilterAttribute to inherit the ActionFilterAttribute and override the OnActionExecuting method to complete verification.

Public class LoginCheckFilterAttribute: ActionFilterAttribute {// indicates whether to check logon public bool IsCheck {get; set ;}// this method is executed before the Action method is executed. public override void OnActionExecuting (ActionExecutingContext filterContext) {base. onActionExecuting (filterContext); if (IsCheck) {// check whether the user has logged on to if (filterContext. httpContext. session ["loginUser"] = null) {// jump to the login page filterContext. httpContext. response. redirect ("/UserLogin/Index ");}}}}

How can this filter work?

Step: 1. Register a Global filter for the MVC program in the Global. asax file and call FilterConfig. RegisterGlobalFilters (GlobalFilters. Filters ). The FilterConfig class is in the App_Start folder (automatically generated when a new MVC project is created). In the static FilterConfig method, public static void RegisterGlobalFilters (GlobalFilterCollection filters) registers the global filter.

Public class FilterConfig {// This method is used to register a Global filter (called in Global) public static void RegisterGlobalFilters (GlobalFilterCollection filters) {// filters. add (new handleerrorattriters (); filters. add (new LoginCheckFilterAttribute () {IsCheck = true });}}

Note that you must assign true to the IsCheck attribute of the feature class instance; otherwise, Session verification does not take effect.

In this way, the LoginCheckFilterAttribute feature will take effect for controllers and actions in the entire MVC program. That is to say, the OnActionExecuting method in the feature class will be called before the Action method is executed, in this way, when accessing the website, the user will first check whether the user has logged on. If the user has not logged on, the logon page will be displayed.

But! But! The problem is that we are registering a global filter. This filter feature takes effect for all the actions under the controller, when you access the website (for example, if we register the default route as/Home/Index), it will first jump to/Home/Index. At this time, the Index method will not be executed and OnActionExecuting () will be executed first () check, found that the Session is null, Response. redirect ("/UserLogin/Index") jumps to the logon page. At this time, we still cannot see the logon page in the browser. Why? Remember the global filter we registered. The target object includes actions under all controllers, and also/UserLogin/Index. When the code reaches this point, the OnActionExecuting () method will be executed again, we found that Session ["UserInfo" =] null and jumped to the logon page again. We couldn't even see the logon page. We certainly couldn't enter the user name and password, and the Session won't have logon information, the browser will return an error page "This page contains a redirection loop", that is, it will continuously redirect to the login page, similar to an endless loop, the browser certainly went on strike ..

How can we solve this bug?

Solution: add features to the UserLoginController

[LoginCheckFilterAttribute (IsCheck = false)] // sets the user logon verification feature (IsCheck is set to false to prevent this controller from working, but to other controllers and actions to prevent redirection loops) public class UserLoginController: Controller {...}

When defining this feature class, we have a bool attribute IsCheck, which indicates whether it is verified. If it is set to false, it indicates that it is not verified. By the way, LoginCheckFilterAttribute can omit the suffix Attrbute.

Make sure to set this feature on the controller. Do not only apply to an Action below, because there are actions that generate verification codes and actions that process login requests, they do not require session verification (meaningless). Adding a feature to the Controller will take effect for all the actions under it, and you do not need to set features for each Action to save the amount of code. We have registered a global filter and separately set the filter feature for the UserLoginController Controller. Here, there is a priority issue: Action> Controller> global, and UserLoginController will not be affected by the global filter. Enter the website address to go To the logon page. Solve the problem.

 

This article mainly references http://www.cnblogs.com/look_sun/p/4425083.html. When I encountered this problem, I read this article and encountered the same problems during development. However, the global filter written by the Buddy seems to be faulty. You only need to judge the Session ["userinfo"] = null. Then, he can set the Session ["userinfo"]! = Null, and jump. When you click "Log on", It redirects to/Home/Index, but at Home, it will be an endless loop.

A very good screen filter in MVC: http://pan.baidu.com/s/1i5zwhjZ reply I want to discuss the issue after Password

Related Article

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.