解读ASP.NET 5 & MVC6系列教程(10):Controller与Action

2019-05-22 14:11:35刘景俊

该实现方法,通过一个内部的IsAction方法来判断该方法是否是一个真正的Action方法,具体代码如下:

protected virtual bool IsAction([NotNull] TypeInfo typeInfo, [NotNull] MethodInfo methodInfo)
{
 // The SpecialName bit is set to flag members that are treated in a special way by some compilers
 // (such as property accessors and operator overloading methods).
 if (methodInfo.IsSpecialName) // 不能是特殊名称(如重载的操作符或属性访问器)
 {
  return false;
 }

 if (methodInfo.IsDefined(typeof(NonActionAttribute))) // 不能声明NonActionAttribute特性
 {
  return false;
 }

 // Overriden methods from Object class, e.g. Equals(Object), GetHashCode(), etc., are not valid.
 if (methodInfo.GetBaseDefinition().DeclaringType == typeof(object)) //不能是重载的方法,比如Equals和GetHashCode
 {
  return false;
 }

 // Dispose method implemented from IDisposable is not valid
 if (IsIDisposableMethod(methodInfo, typeInfo)) // 不能是Dispose方法
 {
  return false;
 }

 if (methodInfo.IsStatic) // 不能是静态方法
 {
  return false;
 }

 if (methodInfo.IsAbstract) // 不能是抽象方法
 {
  return false;
 }

 if (methodInfo.IsConstructor) // 不能是构造函数
 {
  return false;
 }

 if (methodInfo.IsGenericMethod) // 不能是泛型方法
 {
  return false;
 }

 return
  methodInfo.IsPublic; // 必须是Public方法
}

以上内容就是关于Controller和Action查找相关的重要代码,详细原理步骤,请参考Microsoft.AspNet.Mvc.Core程序集下的所有源码。