ASP.NET MVC 請求處理最終落實於 Action 方法執行,而 Action 參數的準備依賴模型繫結。ControllerDescriptor、ActionDescriptor、ParameterDescriptor 三大描述對象構成了此流程的元數據骨架。本文聚焦 ControllerDescriptor 及其唯一實作 ReflectedControllerDescriptor。
public abstract class ControllerDescriptor : ICustomAttributeProvider
{
public virtual object[] GetCustomAttributes(bool inherit);
public virtual object[] GetCustomAttributes(Type attributeType, bool inherit);
public virtual bool IsDefined(Type attributeType, bool inherit);
public virtual IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache);
public abstract ActionDescriptor FindAction(ControllerContext controllerContext, string actionName);
public abstract ActionDescriptor[] GetCanonicalActions();
public virtual string ControllerName { get; }
public abstract Type ControllerType { get; }
public virtual string UniqueId { get; }
}
ASP.NET MVC 僅提供此具體實作,透過反射解析控制器元數據:
public class ReflectedControllerDescriptor : ControllerDescriptor
{
public ReflectedControllerDescriptor(Type controllerType);
public override object[] GetCustomAttributes(bool inherit);
public override object[] GetCustomAttributes(Type attributeType, bool inherit);
public override IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache);
public override bool IsDefined(Type attributeType, bool inherit);
public override ActionDescriptor FindAction(ControllerContext controllerContext, string actionName);
public override ActionDescriptor[] GetCanonicalActions();
public sealed override Type ControllerType { get; }
}
建構子接收 Type controllerType,內部利用反射快取屬性與方法資訊,效能經優化。
理解 ControllerDescriptor 有助於開發自訂動作選擇器、篩選器提供者,或建構動態控制器發現機制。