asp.net mvc routing, Controller, filter learning Notes

Source: Internet
Author: User
Tags exception handling types of filters

1. Further study routing

First routing in the position, an HTTP request come over, the Web container received later, the information to the routing (routing component), routing again to deal with ~ so routing role

Determine controller, determine action, determine other parameters, and pass the request to Controller and action based on the identified data.

tip : When asp.net mvc preview, the Routing component is still part of ASP.net MVC, and subsequent versions seem to provide System.Web.Routing.dll for Microsoft to compile it into a separate component. This means that the ASP.net MVC project is open source, but the routing component is not open source. The routing component can be used not only in asp.net mvc, but also in WebForm. First, we create a new ASP.net MVC2/3 project, the new good later, directly running why access Localhost/home/index will be passed to The action named Index in HomeController (the index method in the HomeController Class). How to achieve it. in our new project, the Global.asax file has the following methods for registering the route

       public static void RegisterRoutes (RouteCollection routes)
        {
            routes. Ignoreroute ("{resource}.axd/{*pathinfo}");

            Routes. Maproute (
                "Default",//Route name
                "{controller}/{action}/{id}",//URL with parameters
                New {controller = "H ome ", action =" Index ", id = urlparameter.optional}//Parameter defaults
            );

        }

Routes is the application level (global), at the beginning of application, the program registered route, the new project by default only registered a route, look at the code,

Routes. Maproute (
' Default ',//Route name
' {controller}/{action}/{id} ',//URL with parameters
New {controller = "Home", action = "Index", id = urlparameter.optional}//Parameter defaults
);

Maproute The first argument is the name of this route, the second argument is the parameter form of the URL , and {controller} is equivalent to a string. Placeholder in the format method, meaning that it can be any one of the controller names,

Similarly, the action, ID is the same, then why the request/home/index does not have ID this parameter, the third parameter is the routing rule default value , this route default controller is Home,action is index, and the ID, is optional ~ ~ ~ When we request/home/index, will be this route to get, and we directly request http://localhost, when we can to Home/index, routing parameters have default value

Ok, so here we've learned how to register a route, and we're going to try to write a route-by-line custom route.

       Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");

            Custom routing,
            routes.  Maproute (
                "Myroute",//Route name
                "{controller}-{action}",//URL with parameters
                New {controller = "Home", Action = "Index"}//Parameter defaults
            );
            Routes. Maproute (
                "Default",//Route name
                "{controller}/{action}/{id}",//URL with parameters
                New {controller = " Home ", action =" Index ", id = urlparameter.optional}//Parameter defaults
            );

Then restart the program, because routes is application level, after we modify application level information, should exit, otherwise there will be no effect drops, this is a lot of beginners easy to make mistakes. If it is a production environment, you should restart the next Web container.

After we run the program, request the domain name/home-index can request the page, explain our custom route is valid.

The rules for routing here are very flexible, and we can customize that the following routing rules can be

Routes. Maproute (
"Myroute",//Route name
' {controller}-{action}-{1}-{2}-{3} ',//URL with parameters
New {controller = "Home", action = "Index"}//Parameter defaults
);

Maproute () method

Maproute has the following overloaded methods

Maproute (string name, string URL);

Maproute (string name, string URL, object defaults);

Maproute (string name, string URL, string[] namespaces);

Maproute (string name, string URL, object defaults, object constraints);

Maproute (string name, string URL, object defaults, string[] namespaces);

Maproute (string name, string URL, object defaults, object constraints, string[] namespaces);

Name parameter: rule name, optionally named. You cannot duplicate a name, or an error occurs: a route named "Default" already exists in the routing collection. The routing name must be unique.

URL parameters: URL to get the rules of the data, this is not a regular expression, will be identified in the parameters, such as: {controller}/{action} at least need to pass the name and URL parameters can establish a routing (routing) Rules. For example, the rules in an instance can be changed to: routes. Maproute ("Default", "{controller}/{action}");

defaults parameter: The default value for the URL parameter. If a URL is only controller:localhost/home/and we only set up a URL to get the data rule: {controller}/{action} Then the default value specified in the defaults parameter is set for the action parameter. The defaults parameter is of type object, so you can pass an anonymous type to initialize the default value: New {controller = "Home", action = "Index"} An instance of three parameters is used in the Maproute method: routes. Maproute ("Default",//Route name "{controller}/{action}/{id}",//URL with parameters new {controller = "Home", action = "Index", id = ""}//Parameter defaults);

constraints parameter: the type of rule or HTTP request that is used to qualify each parameter. The Constraints property is a RouteValueDictionary object, which is a dictionary table, but the value of this dictionary table can have two types: The string used to define the regular expression. Regular expressions are not case-sensitive. An object that implements the Irouteconstraint interface and contains the Match method. You can specify the parameter format by using regular expressions, such as the controller parameter can only be 4 digits: new {controller = @ "\d{4}"}

The type of the request can currently be restricted through the Irouteconstraint interface. Because the Httpmethodconstraint class is provided in System.Web.Routing, this class implements the Irouteconstraint interface. We can add a limit to the HTTP predicate for a routing rule by adding the key to the RouteValueDictionary Dictionary object "HttpMethod", and the value is a Httpmethodconstraint object. For example, restricting a routing rule can only handle GET requests: HttpMethod = new Httpmethodconstraint ("Get", "POST") View Code

            Routes. Maproute ( 
                 "Default",//Route name 
                 "{controller}/{action}/{id}",//URL with parameters 
                 New {controller = "H ome ", action =" Index ", id =" "},//Parameter defaults 
                 New {controller = @" \d{4} ", HttpMethod = new httpmethodcons Traint ("Get", "POST")} 
                 );

We register such a route to customize the routing with filters

      Routes. Maproute (
                "test",//Route name
                "{controller}-{action}-{id}",//URL with parameters
                New {controller = "Home ", action =" Index "},//Parameter defaults
                New {controller = @" ^\w ", action = @" ^\w ", id = @" ^\d "}
            );

Compile and run, when we request/home-index-11 can request to, and we/home-index-1x this is not match,

What is the use of such a rule? The request can be filtered here, such as our ID can only be a number of types, to prevent some illegal detection

Debugging of Routing Components

Let's say we write the N route, and when we send the request, it's not being parsed by the rules we want, so. We need to debug.

Add the RouteDebug.dll reference to our project and add the following code to the Application_Start method in the Global.asax file to enable routing debugging

        protected void Application_Start ()
        {
            arearegistration.registerallareas ();
            RegisterRoutes (routetable.routes);
            Start the routing table debug
            RouteDebug.RouteDebugger.RewriteRoutesForTesting (routetable.routes);
        

After compiling, we start the program, will find that there is a route tester page, about routedebug matching page information, please check the Routedebug manual.

The Route data request in Route Tester is the routing information for the current request

We request/home/index, from which we can see the 4th route captured.

What is the effect of such a route? I think most SEO friends have experience, level two page and level three page, crawler crawl frequency is obviously not the same, so we can be three or even deeper page structure created two pages ~ This is one of the SEO skills

Note: When we write routing rules, because the routing rules are sequential (in the order in which they are registered), the routing rules that are written may be captured and processed by the rules in front of it. The route that is registered later is invalid

2, Controller learning

In asp.net mvc, a controller can contain multiple action. Each action is a method that returns a ActionResult instance.

The ActionResult class includes the Executeresult method, which is executed when the ActionResult object returns.

Controller Processing Process:

  1. Page processing process Send request –> urlroutingmodule capture Request –> Mvcroutehandler.gethttphandler () –> Mvchandler.processrequest

  2.mvchandler.processrequest () processing process: Get specific controller–> controller.execute () –> free Controller object using factory method

  3.controller.execute () process flow: gets action–> Call action method gets the returned actionresult–> call Actionresult.executeresult ( ) method

  4.actionresult.executeresult () process process: Gets the iview object-> gets the page class-> invokes the Iview.renderview () method based on the paging path in the IView object ( Internal call Page.renderview method)

  the responsibility of the Controller object is to pass data, get the View object (the class that implements the IView interface), and notify the View object to display it.

  the View object functions as a display. Although the displayed method Renderview () is called by controller, Controller is only a "commander" role, and the specific display logic is still in the View object .

Note the connection between the IView interface and the specific viewpage. There are iview objects between controller and view . The ASP.net program provides a The Webformview object implements the IView interface. Webformview is responsible for obtaining a specific Page class based on the virtual directory and then calling Page.renderview ()

the ActionResult in the controller

In controller, every Aciton return is ActionResult, we look at the definition of ActionResult ActionResult

    Summary://Encapsulates the result of ' a ' action method and are     used to perform a framework-level
    //     Ope Ration on behalf of the action method.
    Public abstract class ActionResult
    {
        //Summary:
        //     Initializes a new instance of the System.Web.Mvc.ActionResult class.
        protected ActionResult ();

        Summary://Enables processing of the result of of "by     a custom type"
        //     Inherits From the System.Web.Mvc.ActionResult class.
        //Parameters:
        //Context   :
        //The "context in which" is     executed. The context information includes
        //     the controller, HTTP content, request context, and route data.
        public abstract void Executeresult (ControllerContext context);
    }

About ActionResult derived classes, you can refer to: http://blog.csdn.net/steven_husm/article/details/4641281

3, the study of filter

In an MVC project, the action wants to do something special before or after execution, such as identity checking, behavior interception, and so on, ASP.net MVC provides the following default filter

The ASP.net MVC Framework supports the following types of filters:

1. Authorization Filter-implements the Iauthorizationfilter interface

This type of filter is used to implement user authentication and access authorization to the action. For example, authorize belongs to the authorization filter.

2, Action Filter-Implementation of the Iactionfilter interface

It can contain some logic before or after the action is executed, for example, some filters are specifically used to modify the data returned by the action.

3, Result filter-implementation of the Iresultfilter interface

It can contain some logic before the view result is generated or generated, such as some filters designed to modify the results of a view before it is presented to the browser.

4. Exception filter-implements the Iexceptionfilter interface

It is used to process action or result errors, or to log errors.

The filter's default order of execution is also the same as the ordinal listed above, such as the authorization filter executes before the action filter, and the exception filter is always executed at the end. Of course, you can also set the order of the filter execution according to your needs.

The following is a practical example to illustrate the application, create a new MVC3 project, add a common folder to the project, and add a new class LogUserOperationAttribute.cs Loguseroperationattribute

    public class Loguseroperationattribute:actionfilterattribute
    {public
        override void Onresultexecuted ( ResultExecutedContext filtercontext)
        {
            //todo write log code, here Notice concurrency
            file.appendalltext (@ "C:\log.txt", String. Format ("{0} log", DateTime.Now));
            Base. Onresultexecuted (Filtercontext);
        }
    

Add a new homecontrollers and add a new action--index to the homecontrollers and a view file HomeController

    public class Homecontroller:controller {////Get
        :/home/
        [loguseroperation]
        public ActionResult Index ()
        {return
            View ();
        }
    }

Then save the code, F5 run, when the page is displayed, in the C disk already have log.txt files.

Abstract class ActionFilterAttribute These four methods represent , when the action executes, after the action executes, result returns, result returns. (They are executed in the same order as the following figure)

Of course, we can also add the Global action filter in ASP.net MVC 3.0, which turns this filter into the global filter, and all controller action is executed through the rule of filter. It's a big difference from the attributes we identified in controller or an action, which is the difference between the global and the partial. There are many applications for global Action Filter, such as system privileges and system exception handling.

practical application of gloable filter--System of exception handling

We have all sorts of unpredictable situations in the process of running a program, and an exception to the execution of an action is that our exception information needs to be recorded, and we can mark the action or controller like the example above, But so many action and controller to mark, it's really painful, and ASP.net mvc3 has a global filter, we just have to register our custom filter as the global filter

In the common folder, create a new class CustomHandleErrorAttribute.cs Customhandleerrorattribute

    public class Customhandleerrorattribute:iexceptionfilter 
    {public
        void Onexception (Exceptioncontext Filtercontext)
        {
            file.appendalltext (@ "C:\error.txt", String. Format ("{0} error {1}", DateTime.Now, FilterContext.Exception.Message));
        }
    

In the Global.asax file, the Registerglobalfilters method writes the registration code to register the global filters

     public static void Registerglobalfilters (Globalfiltercollection filters)
        {
            filters. ADD (New Customhandleerrorattribute ());//The logic error of the system filters to handle the
            filters. ADD (New Handleerrorattribute ());
        }

Add a new action--->error homecontroller in the HomeController

    public class Homecontroller:controller {////Get
        :/home/
        [loguseroperation]
        public ActionResult Index ()
        {return
            View ();
        }
        Public ActionResult Error ()
        {
            try
            {
                System.IO.File.Open ("C:\\111111.exe"), System.IO.FileMode.Open);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return View ();
        }
    

After compiling to run the project ~ We request/home/error This action, the program appears unusual, we switch to C disk, found that C disk already has Error.txt file
Register to the global filters all action and result execution will invoke our Customhandleerrorattribute override method.

globalfilters, controllerfilters, actionfilters execution sequence issues

Globalfilters-->controllerfilters-->actionfilters "This is a precondition for execution."

Of course, this is on the premise of marking [AttributeUsage (AttributeTargets.All, AllowMultiple = True)] on the definition of the Customhandleerrorattribute class. Otherwise, if the action is labeled the same as controller, it will only execute filter on the action.

Author: Wolfram Original link

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.