在Mvc源码的ControllerActionInvoker的InvokeAction方法里面有一个FindAction方法,FindAction方法在ControllerDescriptor里面定义为虚方法,而ReflectedControllerDescriptor是继承自ControllerDescriptor。其FindAction方法如下:

public override ActionDescriptor FindAction(ControllerContext controllerContext, string actionName) {
if (controllerContext == null) {
throw new ArgumentNullException("controllerContext");
}
if (String.IsNullOrEmpty(actionName)) {
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");
}
//TODO:获取相应的描述action
MethodInfo matched = _selector.FindActionMethod(controllerContext, actionName);
if (matched == null) {
return null;
} return new ReflectedActionDescriptor(matched, actionName, this);
}

查找Action的方法集中在 _selector.FindActionMethod(controllerContext, actionName)里面,_selector是一个ActionMethodSelector类型。FindActionMethod的源码如下:

public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName) {
//获取别名匹配的方法
List<MethodInfo> methodsMatchingName = GetMatchingAliasedMethods(controllerContext, actionName);
//将没有别名的方法和别名匹配的方法添加到一起
methodsMatchingName.AddRange(NonAliasedMethods[actionName]);
//实现方法的筛选
List<MethodInfo> finalMethods = RunSelectionFilters(controllerContext, methodsMatchingName); switch (finalMethods.Count) {
case :
return null; case :
return finalMethods[]; default://如果找到的方法个数大于1,则抛出异常:方法之间存在不明确调用
throw CreateAmbiguousMatchException(finalMethods, actionName);
}
}

GetMatchingAliasedMethods主要是用来获取别名匹配的方法,所谓的别名方法也就是方法的特性有继承自ActionNameSelectorAttribute类,其代码如下:

internal List<MethodInfo> GetMatchingAliasedMethods(ControllerContext controllerContext, string actionName) {
// find all aliased methods which are opting in to this request
// to opt in, all attributes defined on the method must return true
//注意下面的AliasedMethods
var methods = from methodInfo in AliasedMethods
let attrs = (ActionNameSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionNameSelectorAttribute), true /* inherit */)
where attrs.All(attr => attr.IsValidName(controllerContext, actionName, methodInfo))
select methodInfo; return methods.ToList();
}

注意上面方法中linq表达式的AliasedMethods,他是ActionMethodSelector的一个属性类型是MethInfo数组,对应的还有另外一个属性NonAliasedMethods,它们的命名是自解释的。对于这两个MethInfo数组的初始化是在ActionMethodSelector的构造函数中的PopulateLookupTables()方法

private void PopulateLookupTables() {
//获取Controller下面的所有Action
MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);
//获取有效的方法IsValidActionMethod是一个Predicate委托,为什么还要在这里过滤一次还不是很明白
MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);
//获取定义有别名的函数,也就是方法的特性有ActionNameSelectorAttribute或者ActionNameSelectorAttribute的子类
//IsMethodDecoratedWithAliasingAttribute也是一个Predicate委托,代码:
//return methodInfo.IsDefined(typeof(ActionNameSelectorAttribute), true /* inherit */);
AliasedMethods = Array.FindAll(actionMethods, IsMethodDecoratedWithAliasingAttribute);
//获取没有别名的函数,
NonAliasedMethods = actionMethods.Except(AliasedMethods).ToLookup(method => method.Name, StringComparer.OrdinalIgnoreCase);
}

从上面的代码可以知道,当请求某个控制器下的action时,会获取所有的action作为筛选的对象。回到上面的GetMatchingAliasedMethods,当ActionNameSelectorAttribute的IsValidName方法为真时就会返回一个Action。而FindActionMethod的最后调用的是RunSelectionFilters,这个方法的代码如下:

private static List<MethodInfo> RunSelectionFilters(ControllerContext controllerContext, List<MethodInfo> methodInfos) {
// remove all methods which are opting out of this request
// to opt out, at least one attribute defined on the method must return false List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();
List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>(); foreach (MethodInfo methodInfo in methodInfos) {
ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true /* inherit */);
if (attrs.Length == ) {
matchesWithoutSelectionAttributes.Add(methodInfo);
}
//attr.IsValidForRequest判断是否有添加HttpPost或者HttpGet特性
else if (attrs.All(attr => attr.IsValidForRequest(controllerContext, methodInfo))) {
matchesWithSelectionAttributes.Add(methodInfo);
}
}

RunSelectionFilters就是实现将具有别名action和不具有别名的action实现最后的筛选。

一次错误的实践:今天要实现一个功能,就是当页面有多个submit按钮的时候,将其中一个submit按钮的提交转到一个特殊的action,而其他的submit提交,交由一个action处理,于是就写了下面这段代码:

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MulSubmitActionAttribute : ActionNameSelectorAttribute
{
private string _submitBtnName; public MulSubmitActionAttribute(string submitBtnName)
{
if (String.IsNullOrEmpty(submitBtnName))
{
throw new ArgumentException("参数不能为空", "submitBtnName");
}
this._submitBtnName = submitBtnName; } public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
{
if (this._submitBtnName=="changehandler")//当是changehandler这个按钮提交时就返回真
{
return controllerContext.HttpContext.Request[this._submitBtnName] != null;
}
//其他按钮提交也返回真,错误就在这里,这就造成了这个函数的返回永远是真 //这里返回false才是正确的,而且TestAction上面不用加MulSubmitActionAttribute
return true;
}
}

Controller下对应的代码如下:

[HttpGet]
public ActionResult Index()
{
ViewData["Message"] = "欢迎使用 ASP.NET MVC!";
return View();
} [MulSubmitActionAttribute("other")]
public ActionResult TestAction(Person person)
{
return View();
} [MulSubmitActionAttribute("changehandler")]
public ActionResult ChangeHandler(Person person)
{
return View("ChangeHandler");
}

View代码如下:

  <form action="Index" method="post">
<%=Html.EditorForModel()%>
<input type="submit" value="提交" name="tijiao" />
<input type="submit" value="更改经纪人" name="changehandler" />
</form>

当运行代码的时,点击提交按钮时不会出错,点击更改经纪人按钮,想实现的功能是交给ChangHandler这个action进行处理,但是却出错,抛出System.Reflection.AmbiguousMatchException,提示在Action:TestAction和ChangHandler之间调用不明确。错误的原因是这样的,当点击更改经纪人按钮时,在GetMatchingAliasedMethods方法中,会调用两次MulSubmitActionAttribute的IsValid方法,因为AliasedMethods有两项,分别对应着TestAction和ChangeHandler,这两个action都附加着MulSubmitActionAttribute,构造函数传入的值分别是other和changehandler因此,传入changehandler时,由于这时是点击changehandler按钮提交,所以这时controllerContext.HttpContext.Request[this._submitBtnName] != null为true,传入other时,直接返回true,因此就会找到两个action,也就会抛出异常了。

MVC系统学习7—Action的选择过程的更多相关文章

  1. MVC系统学习3—ModelBinder

    在ASP.NET MVC中,每个请求都被映射到一个Action方法,我们可以在action的方法中定义相应类型的参数,View中通过post.get方式提交的request参数,只要名称一致就会对应到 ...

  2. MVC系统学习1—MVC执行流程

    用MVC来做开发也有一段时间了,但是感觉一直没入门,就徘徊在似懂非懂的层次,和去年刚毕业学习WebForm时一样,当时通过张子阳老兄的几篇文章,明白了请求处理流程,页面生命周期才真正明白了WebFor ...

  3. MVC系统学习6—Filter

    Mvc的过滤器是特性类,可以使我们在执行Action之前,执行Action之后,执行Action发生异常时,编写相关的处理代码实现某些逻辑.下面是四个基本的Filter接口. 上面这四个基本的Filt ...

  4. Mvc系统学习9——Areas学习

    在Mvc2.0中,新增加了一个特性就是Areas.在没有有使用Areas的情况下,我们的Mvc项目组织是下面这样的.当项目庞大的时候,Controllers,Model,View文件下下面势必会有很多 ...

  5. MVC系统学习2—MVC路由

    在MVC下不是通过对物理文件的映射来实行访问的,而是通过定义后的路由Url来实现访问的.在前一篇讲到我们是在全局文件下进行路由配置. routes.MapRoute(                & ...

  6. MVC系统学习5——验证

    其实关于Mvc的验证在上一篇已经有讲过一些了,可以通过在我们定义的Model上面添加相应的System.ComponentModel.DataAnnotations空间下的验证属性.在服务器端通过Mo ...

  7. MVC系统学习4—ModelMetaData

    在Mvc R2中,新引入了一些扩展方法,如后面带一个for的方法,这些扩展方法会根据Model的属性自定生成相应的Html元素,如Html.EditFor(Model=>Model.IsAppr ...

  8. MVC系统学习8——AsyncController

    关于为什么使用异步Controller,这里不做备忘,三岁小孩都懂.主要的备忘是如何使用AsyncController. //这个action以Async结尾,并且返回值是void public vo ...

  9. WebApi官网学习记录---webapi中controller与action的选择

    如果framework找到一个匹配的URI,创建一个包含占位符值的字典,key就是这些占位符(不包括大括号),value来自URI或者默认值,这个字典存储在IHttpRouteData对象中.默认值可 ...

随机推荐

  1. 数据结构RMQ

    RMQ算法介绍 RMQ算法全称为(Range Minimum/Maximum Query)意思是给你一个长度为n的数组A,求出给定区间的最值的下标.当然我们可以采用枚举,但是我们也可以使用线段树来优化 ...

  2. Service官方教程(5)后台服务发送通知、把服务变前台服务。

    1.Sending Notifications to the User (发送通知) Once running, a service can notify the user of events usi ...

  3. 445 Add Two Numbers II 两数相加 II

    给定两个非空链表来代表两个非负整数.数字最高位位于链表开始位置.它们的每个节点只存储单个数字.将这两数相加会返回一个新的链表.你可以假设除了数字 0 之外,这两个数字都不会以零开头.进阶:如果输入链表 ...

  4. mysql之修改字符编码

    目录 统一修改字段编码 修改单个字段编码 修改表字符编码 统一修改字段编码: alter table `tablename` convert to character set utf8; 修改表字符编 ...

  5. 利用Wamp在本地搭建一个wordpress站点

    原文链接:利用Wamp在本地搭建一个wordpress站点 有时候我们会想搭建一个自己的站点,可是由于只是想自己访问,就不是很想为这个站点在买一个服务器和域名,那我们可能首先就想到把自己电脑当做服务器 ...

  6. eval()将json 字符串转换为数组

    json ={ GW:[{id:"655",mc:"董事"},{id:"656",mc:"书记"},{id:" ...

  7. Tinking in Java ---Java的NIO和对象序列化

    前面一篇博客的IO被称为经典IO,因为他们大多数都是从Java1.0开始就有了的:然后今天这篇博客是关于NIO的,所以的NIO其实就是JDK从1.4开始,Java提供的一系列改进的输入/输出处理的新功 ...

  8. iOS开发 数据缓存-数据库

    iOS中数据存储方式 Plist(NSArray\NSDictionary) Preference(偏好设置\NSUserDefaults) NSCoding (NSKeyedArchiver\NSk ...

  9. ZooKeeper系列(四)

    一.配置服务 配置服务是分布式应用所需要的基本服务之一,它使集群中的机器可以共享配置信息中那些公共的部分.简单地说,ZooKeeper可以作为一个具有高可用性的配置存储器,允许分布式应用的参与者检索和 ...

  10. 高阶函数与接口混入和java匿名类

    高阶函数与接口混入和java匿名类. 高阶函数中的组件(参量)函数相当于面向对象中的混入(接口)类. public abstract class Bird { private String name; ...