您的位置:首页 > 其它

Web APi之控制器选择Action方法过程(九)

2015-09-30 21:34 204 查看

前言

前面我们叙述了关于控制器创建的详细过程,在前面完成了对控制器的激活之后,就是根据控制器信息来查找匹配的Action方法,这就是本节要讲的内容。当请求过来时首先经过宿主处理管道然后进入Web API消息处理管道,接着就是控制器的创建和执行控制器即选择匹配的Action方法最终并作出响应(在Action方法上还涉及到模型绑定、过滤器等,后续讲)。从上知,这一系列大部分内容都已囊括,我们这一系列也就算快完事,在后面将根据这些管道事件以及相关的处理给出相应的练习来熟练掌握,希望此系列能帮助到想学习原理之人。

HttpControllerContext

我们回顾下此控制器上下文创建的过程:

HttpControllerContext = controllerContext = new HttpControllerContext(descriptor.Configuration,routeData,request)
{
Controller = controller;
ControllerDescrptor = descriptor
}


从上知以及从其名称可得知,控制器上下文就是将创建的控制器以及其描述信息封装到其中,方便调用而已。接下来就进入控制器上Action方法的选择,请往下看!

ApiController

相信大家对此类并不敏感,只要你创建了Web API控制器都是继承于该类,下面我们来看看此类的定义:

public abstract class ApiController : IHttpController, IDisposable
{
// Fields
private HttpConfiguration _configuration;
private HttpControllerContext _controllerContext;
private bool _disposed;
private ModelStateDictionary _modelState;
private HttpRequestMessage _request;
private UrlHelper _urlHelper;

// Methods
protected ApiController();
public void Dispose();
protected virtual void Dispose(bool disposing);
public virtual Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken);
}


此上知该类为抽象类型,并在其中定义了一个ExecuteAsync()方法,此方法是此类中最重要的一个方法,因为控制器的执行过程就是在此方法中进行,下面我们继续来看看此方法的定义及实现。

public virtual Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
{
if (this._request != null)
{
throw Error.InvalidOperation(SRResources.CannotSupportSingletonInstance, new object[] { typeof(ApiController).Name, typeof(IHttpControllerActivator).Name });
}
this.Initialize(controllerContext);
if (this._request != null)
{
this._request.RegisterForDispose(this);
}
HttpControllerDescriptor controllerDescriptor = controllerContext.ControllerDescriptor;
ServicesContainer controllerServices = controllerDescriptor.Configuration.Services;
HttpActionDescriptor actionDescriptor = controllerServices.GetActionSelector().SelectAction(controllerContext);
HttpActionContext actionContext = new HttpActionContext(controllerContext, actionDescriptor);
}


上述我只列出此节要讲的内容,有关过滤器以及其管道和授权等等都已略去,后续会讲。最重要的就是上述红色标记的四个了,下面我一一来查看:

第一步:HttpControllerDescriptor controllerDescriptor = controllerContenxt.ControllerDescriptor

在创建并激活控制器后其控制器上下文也同时生成,我们从控制器上下文中获得有关控制器的描述即HttpControllerDescriptor

第二步:ServicesContainer controllerServices = controllerDescriptor.Configuration.Services;

从控制器的描述中的属性Configuration即HttpConfiguraion来获得其有关控制器的服务容器即Services

由于第三步涉及到其他类,此时我们将另起一段来叙述,请继续往下看!

HttpActionDescriptor

第三步:HttpActionDescriptor actionDescriptor = controllerServices.GetActionSelector().........

这一步就是重点所在,我们在前面叙述了多次关于服务容器ServicesContainer,这里不过是获得有关具体的服务容器而已,我们看看GetActionSelector方法:

public static IHttpActionSelector GetActionSelector(this ServicesContainer services)
{
return services.GetServiceOrThrow<IHttpActionSelector>();
}


到了这里看过前面的文章相信大家不会陌生,就是从服务器容器中去获得我们注入的具体的实现。我们继续看看其子类DefaultServices具体实现到底是什么  

this.SetSingle<IHttpActionSelector>(new ApiControllerActionSelector());


ApiControllerActionSelector

从上得知,注入的服务为ApiControllerActionSelector类,我们继续追查此类:

public class ApiControllerActionSelector : IHttpActionSelector
{
// Fields
private readonly object _cacheKey;
private ActionSelectorCacheItem _fastCache;
private const string ActionRouteKey = "action";
private const string ControllerRouteKey = "controller";

// Methods
public ApiControllerActionSelector();
public virtual ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor);
private ActionSelectorCacheItem GetInternalSelector(HttpControllerDescriptor controllerDescriptor);
public virtual HttpActionDescriptor SelectAction(HttpControllerContext controllerContext);

// Nested Types
private class ActionSelectorCacheItem
{
// Fields
private readonly ReflectedHttpActionDescriptor[] _actionDescriptors;
private readonly ILookup<string, ReflectedHttpActionDescriptor> _actionNameMapping;
private readonly IDictionary<ReflectedHttpActionDescriptor, string[]> _actionParameterNames;
private readonly HttpMethod[] _cacheListVerbKinds;
private readonly ReflectedHttpActionDescriptor[][] _cacheListVerbs;
private readonly HttpControllerDescriptor _controllerDescriptor;

// Methods
public ActionSelectorCacheItem(HttpControllerDescriptor controllerDescriptor);
private static string CreateAmbiguousMatchList(IEnumerable<HttpActionDescriptor> ambiguousDescriptors);
private ReflectedHttpActionDescriptor[] FindActionsForVerb(HttpMethod verb);
private ReflectedHttpActionDescriptor[] FindActionsForVerbWorker(HttpMethod verb);
private IEnumerable<ReflectedHttpActionDescriptor> FindActionUsingRouteAndQueryParameters(HttpControllerContext controllerContext, IEnumerable<ReflectedHttpActionDescriptor> actionsFound, bool hasActionRouteKey);
public ILookup<string, HttpActionDescriptor> GetActionMapping();
private static bool IsSubset(string[] actionParameters, HashSet<string> routeAndQueryParameters);
private static bool IsValidActionMethod(MethodInfo methodInfo);
private static List<ReflectedHttpActionDescriptor> RunSelectionFilters(HttpControllerContext controllerContext, IEnumerable<HttpActionDescriptor> descriptorsFound);
public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext);

// Properties
public HttpControllerDescriptor HttpControllerDescriptor { get; }
}

private class LookupAdapter : ILookup<string, HttpActionDescriptor>, IEnumerable<IGrouping<string, HttpActionDescriptor>>, IEnumerable
{
// Fields
public ILookup<string, ReflectedHttpActionDescriptor> Source;

// Methods
public LookupAdapter();
public bool Contains(string key);
public IEnumerator<IGrouping<string, HttpActionDescriptor>> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator();

// Properties
public int Count { get; }
public IEnumerable<HttpActionDescriptor> this[string key] { get; }
}
}


在此类中还额外包括两个私有的类: ActionSelectorCacheItem 和 LookupAdaper 。先保留这两个类,我们首先看看SelectAtion()方法

public virtual HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
if (controllerContext == null)
{
throw Error.ArgumentNull("controllerContext");
}
return this.GetInternalSelector(controllerContext.ControllerDescriptor).SelectAction(controllerContext);
}


我们从此方法得知,此方法的实现本质是调用了返回值为 ActionSelectorCacheItem中的方法GetInternalSelector,我们从ActionSelectorCacheItem来猜此方法应该是生成一个控制器方法的缓存对象,所以此ActionSelectorCacheItem类型将是我们接下来介绍的重中之重。它被用来筛选Action()方法我们看看这个类:

private class ActionSelectorCacheItem
{
// Fields
private readonly ReflectedHttpActionDescriptor[] _actionDescriptors;
private readonly ILookup<string, ReflectedHttpActionDescriptor> _actionNameMapping;
private readonly IDictionary<ReflectedHttpActionDescriptor, string[]> _actionParameterNames;
private readonly HttpMethod[] _cacheListVerbKinds;
private readonly ReflectedHttpActionDescriptor[][] _cacheListVerbs;
private readonly HttpControllerDescriptor _controllerDescriptor;

// Methods
public ActionSelectorCacheItem(HttpControllerDescriptor controllerDescriptor);
public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext);

// Properties
public HttpControllerDescriptor HttpControllerDescriptor { get; }
}


以上四个属性并返回为相应的返回值是筛选方法的五个步骤之一,还有一个当然是构造函数的初始化了,这一切都将在构造函数中进行筛选,查看其构造函数:

public ActionSelectorCacheItem(HttpControllerDescriptor controllerDescriptor)
{
this._actionParameterNames = new Dictionary<ReflectedHttpActionDescriptor, string[]>();
this._cacheListVerbKinds = new HttpMethod[] { HttpMethod.Get, HttpMethod.Put, HttpMethod.Post };
this._controllerDescriptor = controllerDescriptor;
MethodInfo[] infoArray2 = Array.FindAll<MethodInfo>(this._controllerDescriptor.ControllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance), new Predicate<MethodInfo>(ApiControllerActionSelector.ActionSelectorCacheItem.IsValidActionMethod));
this._actionDescriptors = new ReflectedHttpActionDescriptor[infoArray2.Length];
for (int i = 0; i < infoArray2.Length; i++)
{
MethodInfo methodInfo = infoArray2[i];
ReflectedHttpActionDescriptor key = new ReflectedHttpActionDescriptor(this._controllerDescriptor, methodInfo);
this._actionDescriptors[i] = key;
HttpActionBinding actionBinding = key.ActionBinding;
this._actionParameterNames.Add(key, (from binding in actionBinding.ParameterBindings
where (!binding.Descriptor.IsOptional && TypeHelper.IsSimpleUnderlyingType(binding.Descriptor.ParameterType)) && binding.WillReadUri()
select binding.Descriptor.Prefix ?? binding.Descriptor.ParameterName).ToArray<string>());
}
this._actionNameMapping = this._actionDescriptors.ToLookup<ReflectedHttpActionDescriptor, string>(actionDesc => actionDesc.ActionName, StringComparer.OrdinalIgnoreCase);
int length = this._cacheListVerbKinds.Length;
this._cacheListVerbs = new ReflectedHttpActionDescriptor[length][];
for (int j = 0; j < length; j++)
{
this._cacheListVerbs[j] = this.FindActionsForVerbWorker(this._cacheListVerbKinds[j]);
}
}


上述用五种颜色来标记五种筛选,我们由上至下一一进行简短解释:

初始化筛选

通过传递进来的HttpControllerDesccriptor对象而给其该类此对象的变量属性,然后根据反射条件 BindingFlags.Public | BindingFlags.Instance 来获得控制器中的所有方法,最终保存在MethodInfo[]数组中。

ReflectedHttpActionDescriptor[] _actiondescriptors初始化

ReflectedHttpActionDescriptor是一个抽象类,通过上述已经控制器中的方法封装到MethodInfo[]数组中,此时将循环此数组并将每一个MehodInfo实例封装成ReflectedHttpActionDescriptor对象,并将每个实例封装到此对象数组中,通过该类名称,顾名思义也知,通过反射来获取Action方法的元数据信息。

IDictionary<ReflectedHttpActionDesciptor,string[]> _actionparameterNames初始化

利用获得的ReflectedHttpActionDescriptor进行分析,并将其放到字典中,将此类作为键,而该方法的参数名称。

ILookup<string,ReflectedHttpActionDescriptor> _actionNameMapping初始化 

还是利用获得ReflectedHttpActionDescriptor来依据Action()方法名称来进行分组。

ReflectedHttpActionDescriptor[][] _cacheListVerbs初始化

利用获得的ReflectedHttpActionDescriptor进行依据Http方法类型来进行分类。

上面的五个只是初始化赋值,是为了下面筛选Action名称做准备,似乎有点难以理解,请看下面我们一一进行讲解!

Action名称筛选

既然是筛选名称则要用到 ActionSelectorCacheItem 中的 SelectAction() 方法了,我们来仔细看看此方法的定义及实现:

public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
string str;
ReflectedHttpActionDescriptor[] descriptorArray;
Func<ReflectedHttpActionDescriptor, bool> predicate = null;
bool hasActionRouteKey = controllerContext.RouteData.Values.TryGetValue<string>("action", out str);
HttpMethod incomingMethod = controllerContext.Request.Method;
if (hasActionRouteKey)
{
ReflectedHttpActionDescriptor[] source = this._actionNameMapping[str].ToArray<ReflectedHttpActionDescriptor>();
if (source.Length == 0)
{
throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, Error.Format(SRResources.ResourceNotFound, new object[] { controllerContext.Request.RequestUri }), Error.Format(SRResources.ApiControllerActionSelector_ActionNameNotFound, new object[] { this._controllerDescriptor.ControllerName, str })));
}
if (predicate == null)
{
predicate = actionDescriptor => actionDescriptor.SupportedHttpMethods.Contains(incomingMethod);
}
descriptorArray = source.Where<ReflectedHttpActionDescriptor>(predicate).ToArray<ReflectedHttpActionDescriptor>();
}
else
{
descriptorArray = this.FindActionsForVerb(incomingMethod);
}
if (descriptorArray.Length == 0)
{
throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, Error.Format(SRResources.ApiControllerActionSelector_HttpMethodNotSupported, new object[] { incomingMethod })));
}
IEnumerable<ReflectedHttpActionDescriptor> descriptorsFound = this.FindActionUsingRouteAndQueryParameters(controllerContext, descriptorArray, hasActionRouteKey);
List<ReflectedHttpActionDescriptor> list = RunSelectionFilters(controllerContext, descriptorsFound);
descriptorArray = null;
descriptorsFound = null;
switch (list.Count)
{
case 0:
throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, Error.Format(SRResources.ResourceNotFound, new object[] { controllerContext.Request.RequestUri }), Error.Format(SRResources.ApiControllerActionSelector_ActionNotFound, new object[] { this._controllerDescriptor.ControllerName })));

case 1:
return list[0];
}
string str2 = CreateAmbiguousMatchList((IEnumerable<HttpActionDescriptor>) list);
throw Error.InvalidOperation(SRResources.ApiControllerActionSelector_AmbiguousMatch, new object[] { str2 });
}


我们通过前面的行号来讲解,我们知道在Web API的配置文件中默认是没有Action方法,当然你也手动配置Action方法,所以此时就会出现两种情况,由上亦知:

(6)我们从控制器上下文中获取路由对象RouteData,并且在其Values属性中查找action对应的值并返回该值

若注册路由中有Action名称  

当查找到有Action名称时,看(10)根据上述初始化的_actionNameMapping来获得相应的action方法的元数据信息并返回一个ReflectedHttpActionDescriptor数组也就是source。再看(17)我们从ReflectedHttpActionDescriptor的属性集合SupportedHttpMethods即Http支持的方法中去找到根据从(7)控制器上下文中获得请求过来的Http方法,最后以(17)为条件获取到满足条件的元数据信息ReflectedHttpActionDescriptor数组即descriptorArray中。

关于此注册路由有Action名称的例子就不再叙述,与在MVC框架中请求Action方法类似。

若注册路由无Action名称,则依据Http方法来决定Action方法名称

此时则利用上述初始化依据Http方法类型分类的_cacheListVerbs根据控制器上下文请求过来的方法类型来进行筛选决定其Http方法 ,我们举例来说明:

我们配置其路由为:  

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);


我们的Action方法为:

public void GetProduct(int id) { }

public void PostProduct(int id) { }

public void PutProduct(int id) { }

public void DeleteProduct(int id) { }

public void HeadProduct(int id) { }


当我们进行如下Get请求时:

$.ajax({
type: "get",
url: "http://localhost:7114/api/product/1",
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function (r) {
console.log(r);
}
});


此时会匹配到对应的如下Action方法:


其他的方法请求也类似Get除了Post之外,下面我们进行Post请求:  


观察此结果似乎也没什么不一样,No,我们在Action方法里再添加一个方法如下:

public void Other(int id) { }


接下来我们再来进行Post请求,你会接收到如下响应错误


{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nVoid PostProduct(Int32) on type MvcWebApi.Controllers.ProductController\r\nVoid Other(Int32) on type MvcWebApi.Controllers.ProductController".......}


出错原因是有多个Action方法被匹配到,那么为什么会出现这样的错误呢?这就要说到约定了:

定义在控制器上的Action方法默认是仅支持一种Http方法,并且这个支持的Http方法决定于Action方法的名称,明确来讲,具有以上Action方法的前缀与对应的Http方法将默认支持,比如以上的GetProduct,那么默认只支持Get。但是如果Action名称没有这样的前缀,如以上的Other方法,那么默认支持Post。

基于以上默认约定,所以此时PostProduct和Other都会被匹配到,但是Action默认又仅支持一种Http方法,所以此时会出现如上错误。

这种有Action方法决定它所支持的Http方法的策略与RESET架构风格完全吻合,因为后者推荐直接采用Http方法来表示针对目标资源的操作方式,题外话,但是很多情况下,我们需要一个Action方法既支持Get又支持Post方法这个时候就需要用到ActionHttpMethodProvider特性解决。  

依据请求参数名称及个数筛选 

有参数

在这种情况下,会先把路由数据对象的Values属性中的Keys值存放在一个集合A中,然后再获取当前请求的查询字符串集合,并且把集合中的所有Key值添加到集合A中,这就使的所有请求的参数名称都在一个集合中,然后就会从上述初始化的第二个的结果中根据当前的ReflectedHttpActionDescriptor类型实例(这里是接着上述初始化第三个的流程,所以这里是ReflectedHttpActionDescriptor类型的数组遍历执行)从_actionParameterNames获取对应的参数名称数组,然后是集合A会和获取的参数名称数组做一一的比较,看看集合A中是否包含参数名称,如果都有了则是满足条件。

这里返回的依然可能是ReflectedHttpActionDescriptor类型的数组,因为在一个方法有重载时,比如说Get(stringa)和Get(string a,string b)两个方法时,请求中如果有a和b两个参数的话,Get(string a)也是满足条件的。

无参数

分别是利用 IActionMethodSelector、IActionMethodSelector以及IActionMethodSelector 来实现,就不再叙述,有兴趣的朋友可以查看其源码。

总结

关于控制器的执行选择Action方法用其详细示意图来表示,如下:来源【控制器执行过程】



未完待续:接下来将叙述过滤器,敬请期待。。。。。。。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: