2013年8月1日星期四

Understanding. Net MVC implementation principle Controller / Action

 
  
   

through Reflector decompile, we distribute requests to IIS w3wp.exe process after the analysis of the process by HttpRuntime understanding HttpApplication, HttpModule, HttpHandler, HttpContext generation mechanism. That we continue to learn. Net MVC URL Routing how to jump to a specified Controller / Action process.

   
        
  • UrlRoutingModule
  •     
  • MvcRoutingHandler
  •     
  • MvcHandler
  •     
  • Controller
  •    
   

one, UrlRoutingModule

   

When all HttpModule is loaded for the first HttpApplication, each in its own HttpModule Init method to achieve registration HttpApplication event HttpRequest request interception. Of course UrlRoutingModule no exception. We look UrlRoutingModule decompiled source

   
    View Code     
     
            
     
      [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]       
public class UrlRoutingModule: IHttpModule       
{       
/ / Fields       
private static readonly object _requestDataKey = new object ();       
private RouteCollection _routeCollection;       
      
/ / Methods       
protected virtual void Dispose ()       
{       
}       
      
protected virtual void Init (HttpApplication application)       
{       
application.PostResolveRequestCache + = new EventHandler (this.OnApplicationPostResolveRequestCache);       
application.PostMapRequestHandler + = new EventHandler (this.OnApplicationPostMapRequestHandler);       
}       
      
private void OnApplicationPostMapRequestHandler (object sender, EventArgs e)       
{       
HttpContextBase context = new HttpContextWrapper (((HttpApplication) sender). Context);       
this.PostMapRequestHandler (context);       
}       
      
private void OnApplicationPostResolveRequestCache (object sender, EventArgs e)       
{       
HttpContextBase context = new HttpContextWrapper (((HttpApplication) sender). Context);       
this.PostResolveRequestCache (context);       
}       
      
public virtual void PostMapRequestHandler (HttpContextBase context)       
{       
RequestData data = (RequestData) context.Items [_requestDataKey];       
if (data! = null)       
{       
context.RewritePath (data.OriginalPath);       
context.Handler = data.HttpHandler;       
}       
}       
      
public virtual void PostResolveRequestCache (HttpContextBase context)       
{       
RouteData routeData = this.RouteCollection.GetRouteData (context);       
if (routeData! = null)       
{       
IRouteHandler routeHandler = routeData.RouteHandler;       
if (routeHandler == null)       
{       
throw new InvalidOperationException (string.Format (CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoRouteHandler, new object [0]));       
}       
if (! (routeHandler is StopRoutingHandler))       
{       
RequestContext requestContext = new RequestContext (context, routeData);       
IHttpHandler httpHandler = routeHandler.GetHttpHandler (requestContext);       
if (httpHandler == null)       
{       
throw new InvalidOperationException (string.Format (CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoHttpHandler, new object [] {routeHandler.GetType ()}));       
}       
RequestData data2 = new RequestData ();       
data2.OriginalPath = context.Request.Path;       
data2.HttpHandler = httpHandler;       
context.Items [_requestDataKey] = data2;       
context.RewritePath ("~ / UrlRouting.axd");       
}       
}       
}       
      
void IHttpModule.Dispose ()       
{       
this.Dispose ();       
}       
      
void IHttpModule.Init (HttpApplication application)       
{       
this.Init (application);       
}       
      
/ / Properties       
public RouteCollection RouteCollection       
{       
get       
{       
if (this._routeCollection == null)       
{       
this._routeCollection = RouteTable.Routes;       
}       
return this._routeCollection;       
}       
set       
{       
this._routeCollection = value;       
}       
}       
      
/ / Nested Types       
private class RequestData       
{       
/ / Fields       
[CompilerGenerated]       
private IHttpHandler k__BackingField;       
[CompilerGenerated]       
private string k__BackingField;       
      
/ / Properties       
public IHttpHandler HttpHandler       
{       
[CompilerGenerated]       
get       
{       
return this. k__BackingField;       
}       
[CompilerGenerated]       
set       
{       
this. k__BackingField = value;       
}       
}       
      
public string OriginalPath       
{       
[CompilerGenerated]       
get       
{       
return this. k__BackingField;       
}       
[CompilerGenerated]       
set       
{       
this. k__BackingField = value;       
}       
}       
}       
}       
      
     
     
            
    
   
   

can see UrlRoutingModule subscribe to two HttpApplication events. Which PostResolveRequestCache than PostMapRequestHandler executed first, look PostResolveRequestCache events, starting with his first from RouteCollection get a RouteData object. And RouteCollection created by the routing table

   
    
          
    
     / / Properties      
public RouteCollection RouteCollection      
{      
get      
{      
if (this._routeCollection == null)      
{      
this._routeCollection = RouteTable.Routes;      
}      
return this._routeCollection;      
}      
set      
{      
this._routeCollection = value;      
}      
}     
    
          
   
   

registered in Global.asax.cs route when (ie HttpApplication), has been added to RouteTable.Routes new routing information, so from their own RouteCollection HttpModule can find the corresponding request routing. RouteTable only a static collection property RouteCollection.

   
    View Code     
     
            
     
      public class MvcApplication: System.Web.HttpApplication       
{       
public static void RegisterRoutes (RouteCollection routes)       
{       
routes.IgnoreRoute ("{resource}. axd / {* pathInfo}");       
      
routes.MapRoute (       
"Default", / / ​​Route name       
"{controller} / {action} / {id}", / / ​​URL with parameters       
new {controller = "Home", action = "Index", id = UrlParameter.Optional} / / Parameter defaults       
);       
      
}       
      
protected void Application_Start ()       
{       
AreaRegistration.RegisterAllAreas ();       
RegisterRoutes (RouteTable.Routes);       
      
}       
}      
     
            
    
   
   

UrlRoutingModule in PostResolveRequestCache method reads RouteData routeData <​​strong> = this.RouteCollection.GetRouteData (context);

   

RouteData is included in our registration information for each Route. Registered in the global routing time, MapRote RouteCollection extension method is used by default the MvcRouteHandler.

   
    
          
    
     public static Route MapRoute (this RouteCollection routes, string name, string url, object defaults, object constraints, string [] namespaces)      
{      
if (routes == null)      
{      
throw new ArgumentNullException ("routes");      
}      
if (url == null)      
{      
throw new ArgumentNullException ("url");      
}      
Route route2 = new Route (url, new MvcRouteHandler ());      
route2.Defaults = new RouteValueDictionary (defaults);      
route2.Constraints = new RouteValueDictionary (constraints);      
route2.DataTokens = new RouteValueDictionary ();      
Route item = route2;      
if ((namespaces! = null) && (namespaces.Length> 0))      
{      
item.DataTokens ["Namespaces"] = namespaces;      
}      
routes.Add (name, item);      
return item;      
}      
     
    
    
          
   
   

two, MvcRoutingHandler

   

RouteData structure in addition to the information contained in the Route and the default IRouteHandler that MvcRouteHandler.

   

   Depending on the context in PostResolveRequestCache

compared to the routing table lookup RouteData corresponding post, and through routeHandler.GetHttpHandler (requestContext) obtained MvcHandler instance.

   
    View Code     
     
            
     
      public class MvcRouteHandler: IRouteHandler       
{       
/ / Methods       
protected virtual IHttpHandler GetHttpHandler (RequestContext requestContext)       
{       
return new MvcHandler (requestContext);       
}       
      
IHttpHandler IRouteHandler.GetHttpHandler (RequestContext requestContext)       
{       
return this.GetHttpHandler (requestContext);       
}       
}       
      
     
     
            
    
   
   

three, MvcHandler

   

process can be seen from the above HttpApplication pipeline UrlRouteModule intercept each request, starting RouteCollection find HttpContext request corresponding RouteData (including MvcRouteHandler), and HttpContextBase with RouteData package for the RequestContext, by constructing among injecting MvcHandler. MvcRouteHandler really only played a role in the transition, the real work is HttpApplication pipeline led, in UrlRouteModule and MvcHandler conducted between.

   

UrlRouteModule in PostResolveRequestCache method to MvcHandler through MvcRouteModule get an instance,

   
    
     RequestData data2 = new RequestData ();      
data2.OriginalPath = context.Request.Path;      
data2.HttpHandler = httpHandler;      
context.Items [_requestDataKey] = data2;      
context.RewritePath ("~ / UrlRouting.axd");     
   
   

MvcHandler began to take over the default WebForm the HttpHandler, injected into the medium and loaded context.Items RequestData passed to the pipeline. And this context also be packaged as before the object is injected into the MvcHandler RequestContext, so we MvcHandler subsequent process can also take to the context (Page or Controller, etc.). This is UrlRouteModule RequestData internal private class, so it can not achieve it overloaded, if you want to rewrite UrlRouteModule must realize this class of their own.

   

Thus, to understand and then to MvcHandler MvcRouteHandler from UrlRouteModule to the creation process, but the most important question MvcHandler How does it work? UrlRouteModule intercepted HttpApplication pipeline on request, according to the routing table to find by the RouteData (Routing Information and MvcHandler), replace runs through the entire process of handling requests HttpContext HttpHandler, namely MvcHandler. The work is completed, HttpApplication pipeline to continue processing Step events that ultimately calls the ProcessRequest or BeginProcessRequest MvcHandler methods to enter to the Controller in the process.

   

MvcHandler trigger the process: -> HttpRuntime get to the HttpApplication-> load HttpModule, generate StepManager line and load MvcHandler-> HttpRuntime call HttpApplication.BeginProcessRequest-> HttpApplication. StepManager.ResumeSteps

   

-> execute StepManager in HttpApplication.StepManager._execSteps [i]. Execute -> MvcHandlers.ProcessRequest or BeginProcessRequest

   Here is MvcHandler

decompile source code, you can see that in addition to inherit IHttpHandler, also inherited IRequireSeesionState. Custom HttpHandler want to deal Session words must inherit IRequireSeesionState.

   
    View Code     
     
            
     
      public class MvcHandler: IHttpAsyncHandler, IHttpHandler, IRequiresSessionState       
{       
/ / Fields       
private ControllerBuilder _controllerBuilder;       
private static readonly object _processRequestTag = new object ();       
[CompilerGenerated]       
private static bool k__BackingField;       
[CompilerGenerated]       
private RequestContext k__BackingField;       
internal static readonly string MvcVersion = GetMvcVersionString ();       
public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version";       
      
/ / Methods       
public MvcHandler (RequestContext requestContext)       
{       
if (requestContext == null)       
{       
throw new ArgumentNullException ("requestContext");       
}       
this.RequestContext = requestContext;       
}       
      
protected internal virtual void AddVersionHeader (HttpContextBase httpContext)       
{       
if (! DisableMvcResponseHeader)       
{       
httpContext.Response.AppendHeader (MvcVersionHeaderName, MvcVersion);       
}       
}       
      
protected virtual IAsyncResult BeginProcessRequest (HttpContext httpContext, AsyncCallback callback, object state)       
{       
HttpContextBase base2 = new HttpContextWrapper (httpContext);       
return this.BeginProcessRequest (base2, callback, state);       
}       
      
protected internal virtual IAsyncResult BeginProcessRequest (HttpContextBase httpContext, AsyncCallback callback, object state)       
{       
BeginInvokeDelegate delegate4 = null;       
EndInvokeDelegate delegate5 = null;       
Action action2 = null;       
IController controller;       
IControllerFactory factory;       
this.ProcessRequestInit (httpContext, out controller, out factory);       
IAsyncController asyncController = controller as IAsyncController;       
if (asyncController! = null)       
{       
if (delegate4 == null)       
{       
delegate4 = delegate (AsyncCallback asyncCallback, object asyncState) {       
IAsyncResult result;       
try       
{       
result = asyncController.BeginExecute (this.RequestContext, asyncCallback, asyncState);       
}       
catch       
{       
factory.ReleaseController (asyncController);       
throw;       
}       
return result;       
};       
}       
BeginInvokeDelegate beginDelegate = delegate4;       
if (delegate5 == null)       
{       
delegate5 = delegate (IAsyncResult asyncResult) {       
try       
{       
asyncController.EndExecute (asyncResult);       
}       
finally       
{       
factory.ReleaseController (asyncController);       
}       
};       
}       
EndInvokeDelegate endDelegate = delegate5;       
SynchronizationContext synchronizationContext = SynchronizationContextUtil.GetSynchronizationContext ();       
return AsyncResultWrapper.Begin (AsyncUtil.WrapCallbackForSynchronizedExecution (callback, synchronizationContext), state, beginDelegate, endDelegate, _processRequestTag);       
}       
if (action2 == null)       
{       
action2 = delegate {       
try       
{       
controller.Execute (this.RequestContext);       
}       
finally       
{       
factory.ReleaseController (controller);       
}       
};       
}       
Action action = action2;       
return AsyncResultWrapper.BeginSynchronous (callback, state, action, _processRequestTag);       
}       
      
protected internal virtual void EndProcessRequest (IAsyncResult asyncResult)       
{       
AsyncResultWrapper.End (asyncResult, _processRequestTag);       
}       
      
private static string GetMvcVersionString ()       
{       
return new AssemblyName (typeof (MvcHandler). Assembly.FullName). Version.ToString (2);       
}       
      
protected virtual void ProcessRequest (HttpContext httpContext)       
{       
HttpContextBase base2 = new HttpContextWrapper (httpContext);       
this.ProcessRequest (base2);       
}       
      
protected internal virtual void ProcessRequest (HttpContextBase httpContext)       
{       
IController controller;       
IControllerFactory factory;       
this.ProcessRequestInit (httpContext, out controller, out factory);       
try       
{       
controller.Execute (this.RequestContext);       
}       
finally       
{       
factory.ReleaseController (controller);       
}       
}       
      
private void ProcessRequestInit (HttpContextBase httpContext, out IController controller, out IControllerFactory factory)       
{       
this.AddVersionHeader (httpContext);       
this.RemoveOptionalRoutingParameters ();       
string requiredString = this.RequestContext.RouteData.GetRequiredString ("controller");       
factory = this.ControllerBuilder.GetControllerFactory ();       
controller = factory.CreateController (this.RequestContext, requiredString);       
if (controller == null)       
{       
throw new InvalidOperationException (string.Format (CultureInfo.CurrentUICulture, MvcResources.ControllerBuilder_FactoryReturnedNull, new object [] {factory.GetType (), requiredString}));       
}       
}       
      
private void RemoveOptionalRoutingParameters ()       
{       
RouteValueDictionary values ​​= this.RequestContext.RouteData.Values;       
foreach (string str in values.Where > (delegate (KeyValuePair entry) {       
return (entry.Value == UrlParameter.Optional);       
}). Select , string> (delegate (KeyValuePair entry) {       
return entry.Key;       
}). ToArray ())       
{       
values.Remove (str);       
}       
}       
      
IAsyncResult IHttpAsyncHandler.BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData)       
{       
return this.BeginProcessRequest (context, cb, extraData);       
}       
      
void IHttpAsyncHandler.EndProcessRequest (IAsyncResult result)       
{       
this.EndProcessRequest (result);       
}       
      
void IHttpHandler.ProcessRequest (HttpContext httpContext)       
{       
this.ProcessRequest (httpContext);       
}       
      
/ / Properties       
internal ControllerBuilder ControllerBuilder       
{       
get       
{       
if (this._controllerBuilder == null)       
{       
this._controllerBuilder = ControllerBuilder.Current;       
}       
return this._controllerBuilder;       
}       
set       
{       
this._controllerBuilder = value;       
}       
}       
      
public static bool DisableMvcResponseHeader       
{       
[CompilerGenerated]       
get       
{       
return k__BackingField;       
}       
[CompilerGenerated]       
set       
{       
k__BackingField = value;       
}       
}       
      
protected virtual bool IsReusable       
{       
get       
{       
return false;       
}       
}       
      
public RequestContext RequestContext       
{       
[CompilerGenerated]       
get       
{       
return this. k__BackingField;       
}       
[CompilerGenerated]       
private set       
{       
this. k__BackingField = value;       
}       
}       
      
bool IHttpHandler.IsReusable       
{       
get       
{       
return this.IsReusable;       
}       
}       
}       
      
      
     
     
            
    
   
   

four, Controller debut

   

look MvcHandler's ProcessRequest or BeginProcessRequest, we look at the details of the ProcessRequest method

   
    
          
    
     protected internal virtual void ProcessRequest (HttpContextBase httpContext)      
{      
IController controller;      
IControllerFactory factory;      
this.ProcessRequestInit (httpContext, out controller, out factory);      
try      
{      
controller.Execute (this.RequestContext);      
}      
finally      
{      
factory.ReleaseController (controller);      
}      
}      
     
private void ProcessRequestInit (HttpContextBase httpContext, out IController controller, out IControllerFactory factory)      
{      
this.AddVersionHeader (httpContext);      
this.RemoveOptionalRoutingParameters ();      
string requiredString = this.RequestContext.RouteData.GetRequiredString ("controller");      
factory = this.ControllerBuilder.GetControllerFactory ();      
controller = factory.CreateController (this.RequestContext, requiredString);      
if (controller == null)      
{      
throw new InvalidOperationException (string.Format (CultureInfo.CurrentUICulture, MvcResources.ControllerBuilder_FactoryReturnedNull, new object [] {factory.GetType (), requiredString}));      
}      
}     
    
          
   
   

mainly through ProcessRequestInit Get IControllerFactory the factory, and then through the address in the context of reflection Controller instance. That the factory where they come from?

   

factory = this.ControllerBuilder.GetControllerFactory (); look at this ControllerBuilder is not very familiar with? Look Global.asax.cs code

   
    View Code     
     
            
     
      using System;       
using System.Collections.Generic;       
using System.Linq;       
using System.Web;       
using System.Web.Mvc;       
using System.Web.Routing;       
using System.Threading;       
      
namespace MvcApplication       
{       
/ / Note: For instructions on enabling IIS6 or IIS7 classic mode,       
/ / visit http://go.microsoft.com/?LinkId=9394801       
public class MvcApplication: System.Web.HttpApplication       
{       
# region       
public static void RegisterRoutes (RouteCollection routes)       
{       
/ / routes.IgnoreRoute ("{resource}. axd / {* pathInfo}");       
      
routes.MapRoute (       
"Default", / / ​​Route name       
"{controller} / {action} / {id}", / / ​​URL with parameters       
new {controller = "Home", action = "Index", id = UrlParameter.Optional} / / Parameter defaults       
);       
}       
# endregion       
      
protected void Application_Start ()       
{       
AreaRegistration.RegisterAllAreas ();       
RegisterRoutes (RouteTable.Routes);       
/ / DefaultControllerFactory every time depending on the context of the Action String instance reflection Controller       
/ / You can override DefaultControllerFactory achieve Controller using the IOC container instantiates work (efficiency)       
ControllerBuilder.Current.SetControllerFactory (new DefaultControllerFactory ()); / / Controller reflection plant       
      
}       
}       
}      
     
            
    
   
   

generally we will put ControllerFactory injected at this time, using the default DefaultControllerFactory or their use to achieve new ControllerFactory IOC container factory.
In ControllerFactory Get Controller and perform the controller.Execute (this.RequestContext), entered the Controller of the specific business.

   

IController interface has only one method, ControllerBase inheritance IController, Controller also inherited achieve ControllerBase, and our specific business Controller names are based on the folder name + Controller, and inherited the Controller.

   
    
     public class AccountController: Controller      
public class HomeController: Controller     
   
   

now if you want to achieve a common business example: authenticate users permissions. Then we can achieve a MyController inherited base class Controller, and then the other XXXController have inherited this MyController. Of course, you can use the Filter MVC provides mechanisms (like AOP interceptors) to achieve these basic business verification, is not much more convenient than the WebForm?

   

Execute method is only implemented in ControllerBase and Controller is a direct inheritance, our Controller is the direct successor of the Controller.

   
    View Code     
     
            
     
      protected virtual void Execute (RequestContext requestContext)       
{       
if (requestContext == null)       
{       
throw new ArgumentNullException ("requestContext");       
}       
this.VerifyExecuteCalledOnce ();       
this.Initialize (requestContext);       
this.ExecuteCore ();       
}       
      
protected virtual void Initialize (RequestContext requestContext)       
{       
this.ControllerContext = new ControllerContext (requestContext, this);       
}       
      
protected abstract void ExecuteCore ();      
     
            
    
   
   

Execute the main business on a ExecuteCore in, and this one ExecuteCore no code, just in the Controller has been overloaded business. (It seems ExecuteCore business or be placed under the Controller, while Initalize just RequestContext encapsulates ControllerContext, Microsoft is very interesting every step of repackaging a context).

   

look at the Controller ExecuteCore business

   
    
          
    
     protected override void ExecuteCore ()      
{      
this.PossiblyLoadTempData ();      
try      
{      
string requiredString = this.RouteData.GetRequiredString ("action");      
if (! this.ActionInvoker.InvokeAction (base.ControllerContext, requiredString))      
{      
this.HandleUnknownAction (requiredString);      
}      
}      
finally      
{      
this.PossiblySaveTempData ();      
}      
}      
     
public IActionInvoker ActionInvoker      
{      
get      
{      
if (this._actionInvoker == null)      
{      
this._actionInvoker = this.CreateActionInvoker ();      
}      
return this._actionInvoker;      
}      
set      
{      
this._actionInvoker = value;      
}      
}      
     
protected virtual IActionInvoker CreateActionInvoker ()      
{      
return new ControllerActionInvoker ();      
}     
    
          
   
   

ExectueCore call this.ActionInvoker.InvokeAction (base.ControllerContext, requiredString)) reflected executed Action. requiredString parameter is the name of Action

   

that before and after implementation of this Action is reflected there are other business do? Remember our. Net mvc see each Action method or Controller base class label is affixed to a number of attributes, Action performed before and what triggered it?

   
        
  • Action Controller's OnActionExecuting first before executing the trigger
  •     
  • Action execution is triggered after the Controller's OnActionExecuted
  •     
  • Action affixed before and after implementation inheritance ActionFilterAttribute attribute tag OnActionExecuting, OnActionExecuted be executed (the Attribute as well as its privileges)
  •    
   

also said ControllerActionInvoker The InvokeAction method before executing the Action and Controller also had inherited attributes and Filter scans look InvokeAction specific content

   
        
   
    View Code     
     
            
     
      public virtual bool InvokeAction (ControllerContext controllerContext, string actionName)       
{       
if (controllerContext == null)       
{       
throw new ArgumentNullException ("controllerContext");       
}       
if (string.IsNullOrEmpty (actionName))       
{       
throw new ArgumentException (MvcResources.Common_NullOrEmpty, "actionName");       
}       
ControllerDescriptor controllerDescriptor = this.GetControllerDescriptor (controllerContext);       
ActionDescriptor actionDescriptor = this.FindAction (controllerContext, controllerDescriptor, actionName);       
if (actionDescriptor == null)       
{       
return false;       
}       
FilterInfo filters = this.GetFilters (controllerContext, actionDescriptor);       
try       
{       
AuthorizationContext context = this.InvokeAuthorizationFilters (controllerContext, filters.AuthorizationFilters, actionDescriptor);       
if (context.Result! = null)       
{       
this.InvokeActionResult (controllerContext, context.Result);       
}       
else       
{       
if (controllerContext.Controller.ValidateRequest)       
{       
ValidateRequest (controllerContext);       
}       
IDictionary parameterValues ​​= this.GetParameterValues ​​(controllerContext, actionDescriptor);       
ActionExecutedContext context2 = this.InvokeActionMethodWithFilters (controllerContext, filters.ActionFilters, actionDescriptor, parameterValues);       
this.InvokeActionResultWithFilters (controllerContext, filters.ResultFilters, context2.Result);       
}       
}       
catch (ThreadAbortException)       
{       
throw;       
}       
catch (Exception exception)       
{       
ExceptionContext context3 = this.InvokeExceptionFilters (controllerContext, filters.ExceptionFilters, exception);       
if (! context3.ExceptionHandled)       
{       
throw;       
}       
this.InvokeActionResult (controllerContext, context3.Result);       
}       
return true;       
}      
     
            
    
   
   

ControllerDescriptor controllerDescriptor = this.GetControllerDescriptor (controllerContext);
ActionDescriptor actionDescriptor = this.FindAction (controllerContext, controllerDescriptor, actionName);
The above two code is to read all of the Action Controller and descriptive information including tag attributes

   

FilterInfo filters = this.GetFilters (controllerContext, actionDescriptor); This code is read in front of all the specific reflective properties

   

ActionExecutedContext context2 = this.InvokeActionMethodWithFilters (controllerContext, filters.ActionFilters, actionDescriptor, parameterValues);

   

first run through InvokeActionMethodWithFilters Action Front intercept method, and then Action, followed by post-intercept method. Is not part of realization of AOP functionality? Of course, it did not do the AOP around intercept feature, but it is an improvement compared to a lot of WebForm.

   

fact, the above InvokeAction how to achieve specific intercept before I did not see it, I was through the implementation of the follow-up of two classes override breakpoints view.

   

five, rewritten Controller with ControllerActionInvoker

   

Here is rewriting the code

   
    View Code     
     
            
     
      using System;       
using System.Collections.Generic;       
using System.Linq;       
using System.Web;       
using System.Web.Mvc;       
using System.IO;       
      
namespace MvcApplication.Module       
{       
public class MyController: Controller       
{       
public MyController ()       
{       
/ / this.ActionInvoker = new MyControllerActionInvoker ();       
}       
      
protected override void OnActionExecuting (ActionExecutingContext filterContext)       
{       
base.OnActionExecuting (filterContext);       
}       
      
protected override void OnActionExecuted (ActionExecutedContext filterContext)       
{       
base.OnActionExecuted (filterContext);       
}       
      
/ / /       
/ / / Action and front and rear with the intercept of the caller of the method       
/ / /
      
/ / /       
protected override IActionInvoker CreateActionInvoker ()       
{       
return new MyControllerActionInvoker ();       
}       
}       
      
public class MyControllerActionInvoker: ControllerActionInvoker       
{       
public override bool InvokeAction (System.Web.Mvc.ControllerContext controllerContext, string actionName)       
{       
if (controllerContext == null)       
{       
throw new ArgumentNullException ("controllerContext");       
}       
if (string.IsNullOrEmpty (actionName))       
{       
/ / throw new ArgumentException (MvcResources.Common_NullOrEmpty, "actionName");       
}       
ControllerDescriptor controllerDescriptor = this.GetControllerDescriptor (controllerContext);       
ActionDescriptor actionDescriptor = this.FindAction (controllerContext, controllerDescriptor, actionName);       
if (actionDescriptor == null)       
{       
return false;       
}       
/ / note here                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                                                                                                                                                                

Awstats analysis Nginx log

 

1.nginx log format setting

 
  
log_format  access  '$remote_addr - $remote_user [$time_local] "$request" ' 
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
 
 

Parameter Description:

 

$ remote_addr with $ http_x_forwarded_for to record the client's ip address;
$ remote_user: used to record the client user name;
$ time_local: used to record the access time and time zone;
$ request: used to record the request url with the http protocol;
$ status: used to record the status of the request; success is 200 ,
$ body_bytes_s ent: Records sent to the client file size of the main content;
$ http_referer: used to record the link from that page to access over;
$ http_user_agent: record customer poison ah browser-related information;

 

2.nginx log cutting script

 
  
#!/bin/bash 

logs_path
="/home/wwwlogs/" #设置日志文件存放目录

pid_path
="/usr/local/nginx/logs/nginx.pid" #设置pid文件

mv ${logs_path}access.log ${logs_path}access_$(date
-d "yesterday" +"%Y%m%d").log #重命名日志文件,将access.log切割为每天的日志文件如access_20130728.log

kill
-USR1 `cat ${pid_path}` #向nginx主进程发信号重新打开日志
 
 

add timing tasks, night 00:00 cutting, crontab-e

 
  
0 0 * * * bash /usr/local/nginx/nginx_log.sh
 
 

3. install and configure awstats

 
  
wget http://awstats.sourceforge.net/files/awstats-7.0.tar.gz  
tar -zxvf awstats-7.0.tar.gz
mv awstats
-7.0 /usr/local/awstats
chown
-R root:root /usr/local/awstats
chmod
-R =rwX /usr/local/awstats
chmod
+x /usr/local/awstats/tools/*.pl
chmod +x /usr/local/awstats/wwwroot/cgi-bin/*.pl
 
 

execution tools directory awstats_configure.pl configuration wizard to create a new statistic

 
  
cd /usr/local/awstats/tools 
.
/awstats_configure.pl
 
 The following are some tips

will:

 
  
-----> Running OS detected: Linux, BSD or Unix    

-----> Check for web server install
Enter full config file path of your Web server.
Example:
/etc/httpd/httpd.conf
Example:
/usr/local/apache2/conf/httpd.conf
Example: c:\Program files\apache group\apache\conf\httpd.conf Config file path (
'none' to skip web server setup):
>none #这里添none并回车,因为我们没有使用apache
 
 Enter the next option after

:

 
  
Your web server config file(s) could not be found.  
You will need to setup your web server manually to declare AWStats
script
as a CGI, if you want to build reports dynamically. See AWStats setup documentation (file docs/index.html)
-----> Update model config file '/usr/local/awstats/wwwroot/cgi-bin/awstats.model.conf' File awstats.model.conf updated.

-----> Need to create a new config file ? Do you want me to build a new AWStats config/profilefile (required if first install) [y/N] ?
 
 

here to choose Y, create a new configuration file

 
  
-----> Define config file name to create 
What
is the name of your web site or profile analysis ?
Example: www.mysite.com
Example: demo
Your web site,
virtual server or profile name:
>nginx #这里输入你要分析的域名,或是随便一个你易记的配置名并回车
 
 

next step is to define your configuration file stored in the path, use the default

 
  
-----> Define config file path In which directory do you plan to store your config file(s) ? 
Default:
/etc/awstats
Directory path to store config file(s) (Enter
for default):
> #直接回车,使用默认路径/etc/awstats
 
 

carriage return after the prompt

 
  
-----> Create config file '/etc/awstats/awstats.nginx.conf'  
Config file
/etc/awstats/awstats.nginx.conf created.
-----> Add update process inside a scheduler Sorry, configure.pl does not support automatic add to cron yet.
You can
do it manually by adding the following command to your cron: /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=nginx
Or
if you have several config files and prefer having only one command: /usr/local/awstats/tools/awstats_updateall.pl now
Press ENTER to
continue...#按回车继续
A SIMPLE config file has been created:
/etc/awstats/awstats.nginx.conf You should have a look inside to check and change manually main parameters.
You can then manually update your statistics
for 'yuyuanchun.com' with command: > perl awstats.pl -update -config=nginx
You can also build
static report pages for 'nginx' with command: > perl awstats.pl -output=pagetype -config=nginx
Press ENTER to finish... #回车完成配置文件的创建
 
 

will generate a default configuration file named awstats.nginx.conf / etc / awstats / directory, modify the configuration file log location

 
  
vi /etc/awstats/awstats.nginx.conf 
LogFile
="/home/wwwlogs/access_%YYYY-0%MM-0%DD-24.log"
 
 

Log Description

 
  
# "LogFile" contains the web, ftp or mail server log file to analyze. 
# You can also use tags
in this filename if you need a dynamic file name
# depending on date or time (Replacement
is made by AWStats at the beginning
# of its execution). This
is available tags :
#
%YYYY-n is replaced with 4 digits year we were n hours ago
#
%YY-n is replaced with 2 digits year we were n hours ago
#
%MM-n is replaced with 2 digits month we were n hours ago
#
%MO-n is replaced with 3 letters month we were n hours ago
#
%DD-n is replaced with day we were n hours ago
#
%HH-n is replaced with hour we were n hours ago
#
%NS-n is replaced with number of seconds at 00:00 since 1970
#
%WM-n is replaced with the week number in month (1-5)
#
%Wm-n is replaced with the week number in month (0-4)
#
%WY-n is replaced with the week number in year (01-52)
#
%Wy-n is replaced with the week number in year (00-51)
#
%DW-n is replaced with the day number in week (1-7, 1=sunday)
# use n
=24 if you need (1-7, 1=monday)
#
%Dw-n is replaced with the day number in week (0-6, 0=sunday)
# use n
=24 if you need (0-6, 0=monday)
# Use
0 for n if you need current year, month, day, hour...
n表示时间间隔,我这里就是分析距离当前今天24小时前(昨日)的日志,改成48就是前两天的日志
 
 

create a directory for recording data awstats

 
  
mkdir -p /var/lib/awstats
 
 

then run awstats in the wwwroot directory awatsts.pl to test

 
  
/usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=nginx
 
 

If you see a prompt similar to the following description of the configuration file are correct on the

 
  
Create/Update database for config "/etc/awstats/awstats.nginx.conf" by AWStats version 7.0 (build 1.964) From data 
in log file "/home/wwwlogs/access.log_20130727"... Phase 1 : First bypass old records, searching new record...
Direct access after last parsed record (after line
43260) Jumped lines in file: 43260 Found 43260 already parsed records.
Parsed lines
in file: 0
Found
0 dropped records,
Found
0 comments,
Found
0 blank records,
Found
0 corrupted records,
Found
0 old records,
Found
0 new qualified records
 
 

4.Nginx for Perl support is not good, so here awstats tool will use the survey results to generate static files

 

first in the webroot directory, create a folder. Example :/ home / www / awstats

 
  
mkdir -p /home/www/awstats
 
 

write a script to run periodically so Awstats static page generation to the directory, vi / usr / local / nginx / sbin / awstats.sh

 
  
/usr/local/awstats/tools/awstats_buildstaticpages.pl -update   
\
-config=nginx -lang=cn -dir=/home/www/awstats/nginx
\
-awstatsprog=/usr/local/awstats/wwwroot/cgi-bin/awstats.pl
 
 

/ usr / local / awstats / tools / awstats_buildstaticpages.pl Awstats static page generation tool
-update-config = nginx update configuration items
-lang = cn language to Chinese
- dir = / home / www / awstats statistics output directory
-awstatsprog = / usr / local / awstats / wwwroot / cgi-bin / awstats.pl Awstats log update program path

 

adding scripts execute permissions

 
  
chmod +x /usr/local/nginx/sbin/awstats.sh
 
 

run the script to generate a bunch of pages if there is a similar

 
  
Launch update process : "/usr/local/awstats/wwwroot/cgi-bin/awstats.pl" -config=nginx -update -configdir= ...... 
Build keywords page:
"/usr/local/awstats/wwwroot/cgi-bin/awstats.pl" -config=nginx -staticlinks
-lang=cn -output=keywords Build errors404 page: "/usr/local/awstats/wwwroot/cgi-bin/awstats.pl"
-config=nginx -staticlinks -lang=cn -output=errors404 20 files built.
Main HTML page
is 'awstats.nginx.html'.
 
 

indicates success, then you can add timed task crontab-e

 
  
00 1 * * * /usr/lcoal/nginx/sbin/awstats.sh #每天凌晨1:00执行
 
 

5. modify nginx configuration file, add the site log analysis results

 
  
server 
{
listen
80;
server_name 192.168.75.28;
index index.html index.htm index.php
default.html default.htm default.php;
root
/home/wwwroot/awstats;
location
^~ /icon/ {
root
/usr/local/awstats/wwwroot;
index index.html;
access_log off;
}
autoindex on;
access_log off;
}
 
 

this visit http://192.168.75.28 you can see the statistical results of the static pages.

 

 

 

 

 

 

 

 

 

 

 

 

Analysis of Java SimpleDateFormat

 

1 Introduction

 

article begins, let's look at a short code, this code can run it?

 
  
 1 package simpledate; 
2
3 import java.text.ParseException;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6
7 public class Format {
8
9 public static void main(String[] args) throws ParseException {
10 String date = "2012-12-12";
11 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
12 Date end = simpleDateFormat.parse(date.trim());
13
14 }
15
16 }
 
 

answer is no, this code will be reported java.text.ParseException error, which I encountered in the project yesterday a small problem, let us read the following explanations come back to see why there is this error.

 

1.1 Introduction

 

 

SimpleDateFormat inherited DateFormat, essentially it is a date through a pattern to control the output style tools.

 

1.2 Constructor

 

its constructor method has four, generally we use the first two on it.

 

 

If you do not want the time specified in the constructor class style, you can also select the first constructor, but you must use it before using the specified style.

 
  
1 public static void main(String[] args) throws ParseException {         
2 SimpleDateFormat format5 = new SimpleDateFormat();
3 Date date = new Date();
4 format5.applyPattern("yyyy-MM-dd");
5 System.out.println(format5.format(date));
6 }
 
 

2 used two methods: parse () and format ()

 

2.1 string to date with the parse method

 

parse () is simple to use as follows:

 

1) construct a SimpleDateFormat object, the constructor argument passed when 'yyyy-MM-dd' representatives in date-01-01 'The date format

 

2) holds a string to be transferred

 

3) Use the SimpleDateFormat parse () method

 
  
1 public static void main(String[] args) throws ParseException { 
2 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
3 String s = "2013-01-01";
4 Date date = simpleDateFormat.parse(s);
5 }
 
 

2.2 date to a string using the format method

 

format () is simple to use as follows:

 

1) construct a SimpleDateFormat object, the constructor argument passed when 'yyyy-MM-dd' representatives in date-01-01 'The date format

 

2) held by a date to be transferred object

 

3) Use the SimpleDateFormat format () method

 
  
1 public static void main(String[] args) throws ParseException { 
2 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
3 Date date = new Date();
4 String s = simpleDateFormat.format(date);
5 }
 
 

3 constructor parameters when SimpleDateFormat Pattern

 

Pattern of the Chinese meaning as a model, samples, where we can be understood as the date for the provisions of the template.

 
  
这样我们就很好的理解了前言部分的代码为什么会出错了,因为它在使用parse()转换的时候没按常理出牌,待转换的String对象和规定的模板完全不同,即"2012-12-12"和"yyyy-MM-dd HH:mm:ss"是不同的样式
 
 So how should

Pattern provides? Java API gives the following specifications:

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996 ; 96
M Month in year Month July ; Jul ; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday ; Tue
a Am / pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am / pm (0-11) Number 0
h Hour in am / pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time ; PST ; GMT-08: 00
Z Time zone RFC 822 time zone -0800
 

Examples of the column is the sample values ​​(U.S. standard), Java API also gives some examples of between dates and strings, but also the U.S. standards.

                                                                                                                                                                                             
Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH: mm: ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d,'' yy" Wed, Jul 4, '01
"h: mm a" 12:08 PM
"hh 'o'' clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K: mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh: mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH: mm: ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH: mm: ss.SSSZ" 2001-07-04T12 :08:56.235-0700
 

Perhaps you are more concerned about is that as China's developers some common date formats which, wait, then see below.

                                                                                                   
Date and Time Pattern Result
"yyyy-MM-dd HH: mm: ss E" 2013-07-04 14:23:55 Thursday
"yyyy years at MM-dd HH mm minutes ss seconds when E" 2013 年 07 月 04 日 14 时 24 分 44 秒 Thursday
" yy / MM / dd HH: mm: ss E " 13/07/04 14:25:33 Thursday
"D-day of the first year, the first year w weeks in January in the first week of W, k in the day when, in the first time zone Z '< / span> the first 185 days of the year, the year's first 27 weeks, in January the first one week, the day 14:00, in the first time zone +0800
 

sample code is as follows:

 
  
 1 public static void main(String[] args) throws ParseException {     
2 SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss E");
3 SimpleDateFormat format2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E");
4 SimpleDateFormat format3 = new SimpleDateFormat("yy/MM/dd HH:mm:ss E");
5 SimpleDateFormat format4 = new SimpleDateFormat("一年中的第D天,一年中的第w个星期,一月中的第W个星期,在一天中k时,在第Z时区");
6 Date date = new Date();
7 System.out.println(format1.format(date));
8 System.out.println(format2.format(date));
9 System.out.println(format3.format(date));
10 System.out.println(format4.format(date));
11 }
 
 

Off memcached shared tomcat session problem

Environment is this:
foreground a nginx, behind two tomcat.
nginx key configuration:



upstream tomcat{ 
        server   127.0.0.1:81; 
        server   127.0.0.1:85; 
         
    } 
server { 
        listen       80; 
        server_name  localhost; 
 
        #charset koi8-r; 
 
        #access_log  logs/host.access.log  main; 
 
        location / { 
            root   html; 
            index  index.html index.htm; 
            proxy_pass  http://tomcat; 
        } 
    ... 
} 


tomcat's context.xml the key code:

<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager" 
   memcachedNodes="n1:localhost:11211"     
   requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$" 
   transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" 
   />     




want to use memcached sharing session, now there is a problem, that is, below the two have the same tomcat jsp, function is to submit a value stored in the session, and the page output value stored in the session. And session id,
After you submit a value, the value will be stored inside the session inside a tomcat, then refresh the page repeatedly, once for a value, which once again shows empty, once again showing the value, so repeat, that session not synchronized, but if the other one tomcat stop, there will be another session value, and then start and stop the tomcat, then stop another tomcat, which is also the same session values.
There is no way to stop the tomcat does not use memcached to keep session sync?
------ Solution -------------------- ------------------------
I come and collect points
you first try to get hold of 8.5k
------ Solution ---------------------------- ----------------
I come and collect points
you first try to get hold of 8.5k
------ Solution ---------------------------- ----------------
I come and collect points
you first try to get hold of 8.5k


------ Solution -------------------------------- ------------
09 years of work can get 4K ah?
------ Solution ---------------------------------------- ----
landlord decisive 10K
------ For reference only ---------------------------- -----------
Replies can get 10 points a day available points! tips: teach you how to quickly get available points
- ----- For reference only ---------------------------------------
Thank you for your replies, 8.5 is a good choice, counteroffer change to 8K can accept,
------ For reference only ------------------ ---------------------
9K try
------ For reference only ----------- ----------------------------
resolutely 9K. . . Do not hesitate. Reflects your values ​​
------ For reference only ----------------------------------- ----
9K bars are the architect of
------ For reference only ----------------------- ----------------
you think 8.5k to 8.5k chant, each company's situation is not the same
------ For reference only --- ------------------------------------
then 8.5 bar. . With the crowd
------ For reference only --------------------------------- ------
8.5 or 9 can be the first tentative 9k
------ For reference only ------------------ ---------------------
  This reply was moderator deleted at 2012-03-14 10:56:49

------ For reference only ---------------------------------- -----
bargain of course is the first reported high and lower. .
------ For reference only -------------------------------------- -
  This reply was moderator deleted at 2012-03-15 12:58:50

------ For reference only ---------------------------------- -----
decisive 9k
------ For reference only ---------------------------- -----------
  This reply was moderator deleted at 2012-03-29 11:00:28

------ For reference only ---------------------------------- -----
How much uncertain, you can sneak out to interview a few times to see how many multi give you, shows you how much energy value, mutatis mutandis, with to.
even if someone can give 12K 15K not sure yet.
If someone can give 12K, the old club only to 8K, then you can consider the jump.
------ For reference only -------------------------------------- -
9K architect of it all

------ For reference only ---------------------------------- -----

This can be considered,
------ For reference only ---------------------- -----------------
I have encountered this problem. Landlord has no solution ah.