Interpretation of ASP. NET 5 & MVC6 series (10): Controller and Action

Source: Internet
Author: User

Interpretation of ASP. NET 5 & MVC6 series (10): Controller and Action

We know that in MVC5 and earlier versions, the lifecycles of the two frameworks are different. In the new version of MVC6, the MVC Controller/Web API Controller has already been integrated into one, this chapter describes the definition and use of Controller and Action, and how to query the corresponding Controller and Action based on the routing in the MVC framework.

Definition and use of Controller & Action

In the new MVC6 framework, a Controller base class is still provided. In addition to Url, RouteData, HttpContext, Request, and Response, A Resovler attribute of the IServiceProvider type is also provided, which is a dependency injection container used to obtain instance objects of the specified type in the current request scope.

It complies with the following rules:

The classes inherited from Microsoft. AspNet. Mvc. Controller must be controllers, regardless of the Controller suffix.

If you do not inherit the custom XXXController of Microsoft. AspNet. Mvc. Controller as the MVC Controller, you must reference the Microsoft. AspNet. Mvc-related assembly.

If you do not want the Controller class that meets the preceding conditions to act as the Controller, you must add the NonControllerAttribute feature to the class.

Similarly, if you do not want to use a method in a Controller as an Action, you must add the NonActionAttribute feature to the method.

Note the following features:

Search Mechanism of Controller

From the above chapter, we know that MVC6 not only supports the normal Controller (inherited from the sub-class of the Controller base class), but also supports the Controller of POCO, in this section, we will study the Controller's search principle and mechanism.

First, to determine whether a class is a Controller, you must first determine the number of datasets in which such classes are defined. Microsoft. aspNet. the IAssemblyProvider interface in the Mvc namespace overwrites all the assemblyprovider classes that may define the Controller. The default implementation of this interface is the DefaultAssemblyProvider class. In this class, the necessary conditions are, the Controller that defines MVC must reference one or more of the following sets. The list is as follows:

 
 
  1. Microsoft.AspNet.Mvc 
  2. Microsoft.AspNet.Mvc.Core 
  3. Microsoft.AspNet.Mvc.ModelBinding 
  4. Microsoft.AspNet.Mvc.Razor 
  5. Microsoft.AspNet.Mvc.Razor.Host 
  6. Microsoft.AspNet.Mvc.TagHelpers 
  7. Microsoft.AspNet.Mvc.Xml 
  8. Microsoft.AspNet.PageExecutionInstrumentation.Interfaces

That is to say, if you define a DLL class library that references Microsoft. AspNet. Mvc, the POCO Controller in it will be considered as the Controller of MVC. In other words, if the POCO Controller class you define does not reference any assembly in the above assembly, these Controller classes will not be considered MVC Controller.

Assembly search

Currently, there are two ways to customize the Controller's search mechanism. The first is to inherit IAssemblyProvider to implement the CandidateAssemblies method (or overload DefaultAssemblyProvider) to define its own logic. The interface is defined as follows:

 
 
  1. public interface IAssemblyProvider 
  2.     IEnumerable CandidateAssemblies { get; } } 

Another method may be relatively simpler, that is, to use the extension method defined on IServicesCollection to define the assembly to be searched:

 
 
  1. services.AddMvc().WithControllersAsServices(new[] 
  2.     typeof(MyController).Assembly, 
  3.     typeof(ExternalPocoController).Assembly 
  4. }); 

After the above code is used, the system will switch DefaultAssemblyProvider to FixedSetAssemblyProvider to implement the above judgment mechanism, that is, searching in a set of fixed ranges.

Assembly screening

After the Assembly is determined, another problem arises. How can we determine whether an assembly references the Assembly listed in the necessary conditions of the above MVC? The answer is: In the GetReferencingLibraries method of the ILibraryManager interface instance in Microsoft. Framework. Runtime, you can find how many assemblies reference one of the above lists. For example, you can find the number of assemblies referenced by Microsoft. AspNet. Mvc according to the Microsoft. AspNet. Mvc assembly. The example is as follows:

 
 
 
  1. var col = this.Resolver.GetRequiredService(); var data = col.GetReferencingLibraries("Microsoft.AspNet.Mvc"); 

The usage code of this function in the default DefaultAssemblyProvider implementation class is as follows:

protected virtual IEnumerable
 
   GetCandidateLibraries() {     if (ReferenceAssemblies == null)     {         return Enumerable.Empty
  
   ();     }      // GetReferencingLibraries returns the transitive closure of referencing assemblies     // for a given assembly.     return ReferenceAssemblies.SelectMany(_libraryManager.GetReferencingLibraries)                                 .Distinct()                                 .Where(IsCandidateLibrary); }
  
 

Controller judgment

After determining the Assembly that meets the necessary conditions, you can traverse all the types in the Assembly and then determine whether the type is Controller. In the Controller judgment of the new version, this function is implemented by an IControllerTypeProvider interface, which provides the ControllerTypes read-only attribute to obtain all the defined controllers. The interface definition is as follows:

 
 
  1. public interface IControllerTypeProvider 
  2.     IEnumerable ControllerTypes { get; } } 

DefaultControllerTypeProvider is the default implementation of this interface. When querying qualified controllers, this default implementation class defines an IsController method to determine whether a type is Controller. The specific logic is as follows:

Protected internal virtual bool IsController ([NotNull] TypeInfo typeInfo, [NotNull] ISet candidateAssemblies) {if (! TypeInfo. isClass) // This type must be a class {return false;} if (typeInfo. isAbstract) // This 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 Public class and not nested. The nested class cannot be Controller {return false;} if (typeInfo. containsGenericParameters) // This class cannot be a generic class {return false;} if (! TypeInfo. Name. EndsWith (ControllerTypeName, StringComparison. OrdinalIgnoreCase )&&! DerivesFromController (typeInfo, candidateAssemblies) // This class ends with a Controller, or inherits from the Controller base class, or its parent class is also a Controller. {Return false;} if (typeInfo. IsDefined (typeof (NonControllerAttribute) // This class cannot set the NonControllerAttribute attribute {return false;} return true ;}

You can also implement the IControllerTypeProvider interface to define your Controller judgment logic. However, with some assembly types fixed, MVC also provides an extension method in IServicesCollection to limit some specific Controller types, example:

 
 
 
  1. services.AddMvc().WithControllersAsServices(new[] 
  2.     { 
  3.         typeof(MyController), 
  4.         typeof(ExternalPocoController) 
  5.     }); 

After using the above Code, the system will switch DefaultControllerTypeProvider to FixedSetControllerTypeProvider to implement the above judgment mechanism, that is, to restrict certain classes as controllers, and Other types cannot be Controller.

Action lookup mechanism

Action Selection is implemented through the default implementation class DefaultActionSelector of the IActionSelector interface. In the implementation of the SelectAsync method, select the most matched Action through context and routing data. The Code is as follows:

 
 
  1. public Task SelectAsync([NotNull] RouteContext context) {    // ... }

You can also determine whether a method is an Action, that is, the IActionModelBuilder interface. The default implementation of this interface is the defaactionactionmodelbuilder class. The implementation method is as follows:

Public IEnumerable BuildActionModels ([NotNull] TypeInfo typeInfo, [NotNull] MethodInfo methodInfo) {if (! IsAction (typeInfo, methodInfo) {return Enumerable. Empty ();} //... omit other code}

This implementation method uses an internal IsAction method to determine whether the method is a real Action method. The specific code is as follows:

 
 
  1. Protected virtual bool IsAction ([NotNull] TypeInfo typeInfo, [NotNull] MethodInfo methodInfo)
  2. {
  3. // The SpecialName bit is set to flag members that are treated in a special way by some compilers
  4. // (Such as property accessors and operator overloading methods ).
  5. If (methodInfo. IsSpecialName) // it cannot be a special name, such as an overloaded operator or attribute accessor)
  6. {
  7. Return false;
  8. }
  9.  
  10. If (methodInfo. IsDefined (typeof (NonActionAttribute) // NonActionAttribute attribute cannot be declared
  11. {
  12. Return false;
  13. }
  14.  
  15. // Overriden methods from Object class, e.g. Equals (Object), GetHashCode (), etc., are not valid.
  16. If (methodInfo. GetBaseDefinition (). DeclaringType = typeof (object) // it cannot be an overloaded method, such as Equals and GetHashCode
  17. {
  18. Return false;
  19. }
  20.  
  21. // Dispose method implemented from IDisposable is not valid
  22. If (IsIDisposableMethod (methodInfo, typeInfo) // it cannot be the Dispose method.
  23. {
  24. Return false;
  25. }
  26.  
  27. If (methodInfo. IsStatic) // cannot be a static method
  28. {
  29. Return false;
  30. }
  31.  
  32. If (methodInfo. IsAbstract) // cannot be an abstract Method
  33. {
  34. Return false;
  35. }
  36.  
  37. If (methodInfo. IsConstructor) // it cannot be a constructor.
  38. {
  39. Return false;
  40. }
  41.  
  42. If (methodInfo. IsGenericMethod) // it cannot be a generic Method
  43. {
  44. Return false;
  45. }
  46.  
  47. Return
  48. MethodInfo. IsPublic; // The Public method must be used.
  49. }

The above content is about the important Code related to Controller and Action Search. For detailed principles and steps, see all the source code under the Microsoft. AspNet. Mvc. Core Assembly.

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.