We know that in the MVC5 and previous versions, the lifecycle of the two frameworks is not the same, in the new MVC6, MVC controller/web API Controller has been combined, this chapter we mainly explain the definition and use of Controller and action, And in the MVC framework, how to query the corresponding controller and action based on routing.
Definition and use of controller&action
In the new MVC6 framework, a controller base class is still provided, where in addition to providing,,,, and Url RouteData HttpContext Request Response Beyond, there is also a IServiceProvider type of Resovler attribute, which belongs to a container of dependency injection, Used to get an instance object of the specified type within the current request scope.
It complies with the following rules:
Inherited Microsoft.AspNet.Mvc.Controller classes are definitely controllers, regardless of whether there is a controller suffix. If you do not inherit Microsoft.AspNet.Mvc.Controller a custom Xxxcontroller to be an MVC controller, you must refer to Microsoft.AspNet.Mvc the relevant assembly. If you do not want the controller class that satisfies the above criteria to be controller, you need to add an attribute to the class NonControllerAttribute . Similarly, if you don't want a method in a controller to act as an action, you need to add an attribute to the method NonActionAttribute .
There are several other features to note:
| characteristic |
Description |
| Actionnameattribute |
Define the name of the action (which can be different from the action method name) |
| Acceptverbsattribute |
Defines the supported HTTP method names and supports single or multiple method. |
| Activateattribute |
An injection-dependent tag that can be placed on a property or field with set permissions. |
| Responsecacheattribute |
Set the client cache for a controller or action. |
| Requirehttpsattribute |
The limit must be an HTTPS request. |
| Remoteattribute |
Marked as an AJAX request, the server side does not validate validation of form forms. |
| Noncontrollerattribute |
Marking the class is not controller. |
| Nonactionattribute |
Mark this method is not an action. |
The search mechanism of controller
From the above chapters, we know that MVC6 not only supports the normal controller (inherited from the Controller base class subclass), but also supports Poco controller, in this section we'll look at the controller principle mechanism.
First, to determine whether a class is controller, you must first decide how many assemblies define such a class. The Microsoft.AspNet.Mvc interface under a namespace IAssemblyProvider is to overwrite the assembly that finds all possible definitions of controller, and the default implementation of the interface is a class in which the DefaultAssemblyProvider necessary condition is to Controller that defines MVC must refer to one or more assemblies in the following assembly, which are listed below:
MICROSOFT.ASPNET.MVC
Microsoft.AspNet.Mvc.Core
Microsoft.AspNet.Mvc.ModelBinding
Microsoft.AspNet.Mvc.Razor
Microsoft.AspNet.Mvc.Razor.Host
Microsoft.AspNet.Mvc.TagHelpers
MICROSOFT.ASPNET.MVC.XML
Microsoft.AspNet.PageExecutionInstrumentation.Interfaces
In other words, if you define a referenced Microsoft.AspNet.Mvc DLL class library, the Poco controller inside it is considered an MVC controller. In other words, if you define a Poco controller class that does not refer to any of the assemblies in the above assembly, those controller classes are not considered to be controller of MVC.
Search for assemblies
There are two ways to customize the controller lookup mechanism, the first of which is to inherit the IAssemblyProvider implementation CandidateAssemblies method (or overload DefaultAssemblyProvider ) to define your own logic. The interface is defined as follows:
Public interface Iassemblyprovider
{
ienumerable<assembly> candidateassemblies {get;}
}
Another way, perhaps relatively simpler, is to use the IServicesCollection extension method defined to define the assembly to find:
Services. Addmvc (). Withcontrollersasservices (new[]
{
typeof (Mycontroller). Assembly,
typeof (Externalpococontroller). Assembly
});
Using the above code, the system will DefaultAssemblyProvider switch FixedSetAssemblyProvider to achieve the above judgment mechanism, namely: in the fixed scope of the assembly to find.
Filtering of assemblies
After you have identified the assembly, another question comes up, how do you determine if an assembly references the assemblies listed in the MVC requirements above? The answer is a method of an Microsoft.Framework.Runtime interface instance in, where ILibraryManager GetReferencingLibraries you can find how many assemblies refer to one of the assemblies in the list above. For example, depending on the assembly, you can Microsoft.AspNet.Mvc find how many assemblies reference the assembly, as shown in the following example:
var col = this. Resolver.getrequiredservice<ilibrarymanager> ();
var data = Col. Getreferencinglibraries ("MICROSOFT.ASPNET.MVC");
This feature is used in the Defaultassemblyprovider default implementation class with the following code:
Protected virtual ienumerable<ilibraryinformation> getcandidatelibraries ()
{
if (referenceassemblies = = null)
{return
enumerable.empty<ilibraryinformation> ();
}
Getreferencinglibraries returns the transitive closure of referencing assemblies
//for a given assembly.
Return Referenceassemblies.selectmany (_librarymanager.getreferencinglibraries)
. Distinct ()
. Where (iscandidatelibrary);
}
The judgment of controller
Once the required assembly is determined, you can iterate through all the types in the assembly and then determine if the type is controller. In the new controller judgment, the function is implemented as an IControllerTypeProvider interface that provides a ControllerTypes read-only property for obtaining all the defined controller, and the interface is defined as follows:
Public interface Icontrollertypeprovider
{
ienumerable<typeinfo> controllertypes {get;}
}
DefaultControllerTypeProvideris the default implementation of this interface, and when querying for controller, the default implementation class defines a IsController method that is used to determine whether a type is controller, with the following specific logic:
protected internal virtual bool Iscontroller ([Notnull] TypeInfo TypeInfo, [Notnull]
Iset<assembly> candidateassemblies) {if (!typeinfo.isclass)//The type must be a class {return false;
} if (typeinfo.isabstract)//The class must not be an abstract class {return false; //We only consider public top-level classes as controllers. IsPublic returns FALSE for nested//classes, regardless of visibility modifiers if (!typeinfo.ispublic)//The class must be a publi
Class C (and not nested), nested classes cannot be controller {return false;
} if (typeinfo.containsgenericparameters)//The class cannot be a generic class {return false; if (!typeinfo.name.endswith (Controllertypename, stringcomparison.ordinalignorecase) &&!
Derivesfromcontroller (TypeInfo, candidateassemblies))//The class ends in controller or inherits from the Controller base class, or its parent is also controller.
{return false;
} if (typeof (Noncontrollerattribute))//The class cannot set Noncontrollerattribute attribute {return false;
return true; }
You can also implement IControllerTypeProvider interfaces to define your own controller judgment logic, but with fixed some assembly types, MVC IServicesCollection also provides an extension method for restricting some controller-specific types, examples are as follows:
Services. Addmvc (). Withcontrollersasservices (new[]
{
typeof (Mycontroller),
typeof (Externalpococontroller)
});
Using the above code, the system will DefaultControllerTypeProvider switch FixedSetControllerTypeProvider to implement the above judgment mechanism, namely: restricting certain classes as controller, other types can not be used as controller.
Action Lookup mechanism
The action selection is implemented through the IActionSelector default implementation class of the interface DefaultActionSelector , in the implemented SelectAsync method, by selecting the most matching action by context and routing data, indicating the following code:
Public task<actiondescriptor> Selectasync ([notnull] routecontext context)
{
//...
}
There is another place to judge whether a method is an action, that is IActionModelBuilder , an interface, the default implementation of the interface is a DefaultActionModelBuilder class, and the implementation method is as follows:
Public ienumerable<actionmodel> buildactionmodels ([notnull] TypeInfo typeinfo,
[Notnull] MethodInfo MethodInfo)
{
if (! Isaction (TypeInfo, methodInfo))
{return
enumerable.empty<actionmodel> ();
}
// .... Omit other code
}
The implementation method, through an internal IsAction method to determine whether the method is a real action method, the specific code is as follows:
Protected virtual bool Isaction ([Notnull] TypeInfo typeinfo, [notnull] MethodInfo MethodInfo) {//the specialname bit I s set to flag members, are treated in a special way by some compilers//(such as property accessors and operator Ove
Rloading methods).
if (methodinfo.isspecialname)//cannot be a special name (such as an overloaded operator or property accessor) {return false;
} if (methodinfo.isdefined typeof (Nonactionattribute))//cannot declare Nonactionattribute attribute {return false;
}//Overriden methods from object class, e.g. Equals (Object), GetHashCode (), etc., are not valid. if (Methodinfo.getbasedefinition ().
DeclaringType = = typeof (object)//cannot be overloaded method, such as Equals and GetHashCode {return false; }//Dispose method implemented from IDisposable are not valid if (Isidisposablemethod (MethodInfo, TypeInfo))//cannot be disp
Ose method {return false;
} if (methodinfo.isstatic)//cannot be static method {return false;
} if (Methodinfo.isabstract)//cannot be abstract method {return false; } if (Methodinfo.isconstructor)//cannot be constructor {return false;
} if (Methodinfo.isgenericmethod)//cannot be a generic method {return false; return methodinfo.ispublic; Must be public method}
The above is about controller and action lookup-related important code, detailed principle steps, please refer to Microsoft.AspNet.Mvc.Core Assembly of all the source.