asp.net MVC2.0 custom filters__.net

Source: Internet
Author: User

Today we all study together under the ASP.net MVC2.0 custom filters, this section mainly studies under ActionFilterAttribute,

ActionFilterAttribute inherits Iactionfilter, Iresultfilter interfaces, and inherits FilterAttribute classes.

ActionFilterAttribute can monitor all phases of the action execution, including logging, exception handling, and so on.

Mainly includes the following four overloaded methods

onactionexecuting,onactionexecuted,onresultexecuting,onresultexecuted

1.OnActionExecuting is performed before the action starts

For authentication and server-side cache output

2. onactionexecuted executes after action ends

Primarily for exception handling

3. Onresultexecuting is executed before returning result

Primarily for client caching and server-side compression

4. onresultexecuted is executed after returning result

Mainly used for exception handling and page tail output debugging information

The following two demo will show the specific usage of actionfilter

Demo1:

In this demo we will show the execution time of the action at various stages and output it in the page.

First we define a Actionlogattribute class

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Using SYSTEM.WEB.MVC; Namespace Mvcappone.actionfilters {public class Actionlogattribute:actionfilterattribute {///<summ
            Ary>///represents ActionId///</summary> public int ID {get;
        Set ///<summary>///Execute///</summary>///<param name= before action starts Filtercon
            Text ' ></param> public override void OnActionExecuting (ActionExecutingContext filtercontext) { FilterContext.RequestContext.HttpContext.Response.Write (ID.
            ToString () + ": Actinon begin Execution" + DateTime.Now.ToString () + "<br/>"); Base.
        OnActionExecuting (Filtercontext); ///<summary>///executes///</summary>///<param name= after action ends Filtercon Text ></param> public override void OnActionExecuted (ActIonexecutedcontext filtercontext) {filterContext.RequestContext.HttpContext.Response.Write (ID).
            ToString () + ": Actinon execution End" + DateTime.Now.ToString () + "<br/>"); Base.
        OnActionExecuted (Filtercontext); ///<summary>///Execute///</summary>///<param name= before result starts Filtercon
            Text ' ></param> public override void Onresultexecuting (ResultExecutingContext filtercontext) { FilterContext.RequestContext.HttpContext.Response.Write (ID.
            ToString () + ": Result execution Start" + DateTime.Now.ToString () + "<br/>"); Base.
        Onresultexecuting (Filtercontext); ///<summary>///executes///</summary>///<param name= "After result end Filtercon"
            Text ' ></param> public override void Onresultexecuted (ResultExecutedContext filtercontext) { FilterContext.RequestContext.HttpContext.Response.Write (ID. TostrinG () + ": Result execution End" + DateTime.Now.ToString () + "<br/>"); Base.
        Onresultexecuted (Filtercontext); }

    }
}


Then we build a view page, Shownews page

Then create an action and mark the attribute on the action

[Actionfilters.actionlog (id=3)]
        Public ActionResult shownews ()
        {return
            View ();
        }


At this point we run the Shownews page and we will see the following effect

Demo2: And then we'll look at the second demo, in this demo, we'll show the role of each method in Actionfilter

We build a class Actiondealattribute

public class Actiondealattribute:actionfilterattribute {public override void OnActionExecuting (actionexecut Ingcontext filtercontext) {//user does not validate through, turn to login page if (!filtercontext.requestcontext.httpcontex t.user.identity.isauthenticated) {Filtercontext.result = new Redirectresult (".
            /account/logon "); } public override void OnActionExecuted (ActionExecutedContext filtercontext) {//exception
                Process if (filtercontext.exception!=null) {filtercontext.exceptionhandled=true; Filtercontext.result = new Redirectresult (".. /shared/error ");//Turn to error page}} public override void Onresultexecuting (ResultExecutingContext f Iltercontext) {base.
        Onresultexecuting (Filtercontext); public override void Onresultexecuted (ResultExecutedContext filtercontext) {base.Onresultexecuted (Filtercontext); }

    }


Create a News page and create a corresponding action

If the Access News page needs to be logged in for access, it will be handled in the onactionexecuting by marking this attribute on the news corresponding action

[Actionfilters.actiondeal]
        Public ActionResult News ()
        {return
            View ();
        }


If an exception occurs when the news page is visited, it is turned to the error page and processed in onactionexecuted

        [Actionfilters.actiondeal]
        public void News ()
        {
            throw new Exception ();
        }


The above is just a simple use of the custom action for your reference.

Code Download: http://download.csdn.net/detail/zx13525079024/4375094

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.