[Translate] logging with ASP. NET MVC action Filter

Source: Internet
Author: User

[Translate] logging with ASP. NET MVC action Filter

Original address: Http://www.singingeels.com/Articles/Logging_with_ASPNET_MVC_Action_Filters.aspx

Translation: Anders Liu

Summary: Logging is a common interleaved concern (cross-cutting Concern), and many ASP. NET developers will handle it in Global.asax files. Since MVC is built on ASP, you can use the same solution, but there is a better way. This article shows you how easy it is to add logs to a Web application using an action filter for ASP.

Logging is a common cross-cutting Concern that many ASP. Developers solve in the Global.asax file. Because MVC is built on top of the ASP. could tap into the same solution, but there is a better to. This article would show how easy it was to add logging to your Web app using the ASP. NET MVC Action Filters.

Logging is a common interleaved concern, and many ASP. NET developers will handle it in the Global.asax file. Since MVC is built on ASP, you can use the same solution, but there is a better way. This article shows you how easy it is to add logs to a Web application using an action filter for ASP.

Action Filters give you the ability to run custom code before or a after a action (or page) is hit. Applying action filters to your MVC app was simple because they was implemented as attributes that can being placed on a metho D (an individual Action), or a class (the entire Controller).

Action filters allow you to run custom code before and after the action (or page) executes. Using action filters in an MVC application is simple because they are implemented by attributes and can be placed in front of a method (a single operation) or a class (the entire controller).

To show how easy it's, we ' re going to take the Out-of-the-box ASP. NET MVC template, and very slightly tweak it to begin Logging. We ll add one class (our custom Action Filter), and salt the existing pages with our new "Logrequest" attribute.

To see how simple this is, we use the out-of-the-box ASP. NET MVC template, and tweak it a little bit to start logging. We will add a class (the Custom action filter) and use this new "Logrequest" feature to "modulate" the existing page.

Creating a Custom Action Filter
Create a custom action filter

To create your own action filter, you simply has to inherit from the base "ActionFilterAttribute" class that ' s already a Part of the MVC framework. Easier on myself, I ' ve also implemented the Iactionfilter interface so, Visual Studio can auto-generate m Y, methods for me.

To create your own action filters, simply inherit the ActionFilterAttribute base class, which is part of the MVC framework. I also implemented the Iactionfilter interface for more convenience, so that Visual Studio would automatically generate two methods for me.

At this point, the My custom action filter looks like this:

At this point, my custom action filter looks like this:

1  Public classLogsrequestsattribute:actionfilterattribute, Iactionfilter2 {  3 voidiactionfilter.onactionexecuted (actionexecutedcontext filtercontext)4 {  5 //I need to does something here ...6 }  7 voidiactionfilter.onactionexecuting (actionexecutingcontext filtercontext)8 {  9 //I need to does something here ...Ten }   One}

The ActionFilterAttribute and Iactionfilter interface comes from the SYSTEM.WEB.MVC namespace.

The ActionFilterAttribute and Iactionfilter interfaces come from the SYSTEM.WEB.MVC namespace.

It's important to remember It's article is written (and the sample app was compiled) for ASP. NET MVC Preview 4. When the beta and release are eventually out, specifics of the article are not being 100% relevant. However, this capability should remain the same.

Remember that this article (and the sample program in the text) was written for ASP. NET MVC Preview 4. When beta and release releases, the details of the article may not be 100% effective. However, this feature is still the same.

Applying our Custom Action Filter
Apply a custom action filter

Now the We have the created our action filter, we need to apply it to our Controllers or optionally and to our Actions. Because logging is something so would likely want on all of your "pages", we'll simply add it at the controller leve L. Here's what we've added to the existing controllers this were supplied in the ASP.

Now that we have created the action filter, we need to apply it to the controller, or selectively apply it to the operation. Because you might want to log all of the pages, we simply add them to the controller level. Here we add it to the two controllers provided by the ASP.

1 //HandleError was already there ...2 [HandleError]3 [Logrequest]4  Public classHomecontroller:controller5 {  6 ...  7 }  8 //HandleError was already there ...9 [HandleError]Ten [Logrequest] One  Public classAccountcontroller:controller A {   - ...   -}

That ' s it! The ASP. NET MVC framework would automatically call our methods (OnActionExecuting and then onactionexecuted) when a request Comes in to any of those and controllers.

That's it! When a request enters these two controllers, the ASP. NET MVC framework automatically calls our method (first onactionexecuting, then onactionexecuted).

At the this point, the all we had to actually implement our logging code. Because I want to is able to easily report against my site's activity, I ' m going to log to a SQL database. Now, it's important to note that action filters is executed synchronously (for obvious reasons), but I don ' t want the use R to has to wait for my logging to happen before he can enjoy my great site. So, I ' m going to use the fire and forget design pattern.

At this point, we have to really implement the log record code. Because I want to be able to simply report on the activity of the site, I log the logs in the SQL database. Note that the action filters are performed synchronously (for obvious reasons), but I don't want users to have to wait to log logs before accessing my awesome site. So I'm going to use fire and forget design mode.

When we ' re all done, this is what our logger would look like:

After all this, our log records look like this:

1 //by the To, I ' m using the Entity Framework for fun. 2  Public classLogrequestattribute:actionfilterattribute, Iactionfilter3 {  4 Private StaticLoggerdatastoreentities DataStore =Newloggerdatastoreentities (); 5 voidiactionfilter.onactionexecuting (actionexecutingcontext filtercontext)6 {  7ThreadPool.QueueUserWorkItem (Delegate  8 {  9Datastore.addtositelog (NewSitelogTen {   OneAction =FilterContext.ActionMethod.Name, AController =filterContext.Controller.ToString (), -TimeStamp =FilterContext.HttpContext.Timestamp, -IPAddress =filterContext.HttpContext.Request.UserHostAddress, the });  - datastore.savechanges ();  - });  - }   +}

Conclusion
Summary

There is a lot of features in MVC this could each merrit their own articles, but Action Filters is definately one featur E that shows off the advantages of the MVC design pattern. Action Filters make perfect sense for cross-cutting concerns like logging, but can get creative with how and why U Se them.

There are too many features in MVC, each of which can be written separately, but action filters can best show the nature of MVC design patterns. Action filters have an unusual meaning for interlaced concerns, but how and why they are used requires you to be creative.

This article isn't here to show you the best-of-the-logging, but rather how and why are you would use ASP. Lters. Here's the source code, play around with It:MVC_CustomActionFilter_Logging.zip

This article does not describe the best way to log logs, but rather gives an idea of how and why ASP is used to manipulate filters. Here is the source code, have fun: Mvc_customactionfilter_logging.zip.

[Translate] log logs using the ASP. NET MVC action filter

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.