ASP.NET MVC 源码分析(二) —— 从 IRouteBuilder认识路由构建
我们来看IRouteBuilder的定义:
public interface IRouteBuilder
{
IRouter DefaultHandler { get; set; } IServiceProvider ServiceProvider { get; } IList<IRouter> Routes { get; } IRouter Build();
}
一个默认的IRouter对象,一个Build方法,一个IRouter集合和一个获取服务对象IServiceProvider。
我们进一步看IRouteBuilder的实现RouterBuilder:
public class RouteBuilder : IRouteBuilder
{
public RouteBuilder()
{
Routes = new List<IRouter>();
} public IRouter DefaultHandler { get; set; } public IServiceProvider ServiceProvider { get; set; } public IList<IRouter> Routes
{
get;
private set;
} public IRouter Build()
{
var routeCollection = new RouteCollection(); foreach (var route in Routes)
{
routeCollection.Add(route);
} return routeCollection;
}
}
主要的实现是Build方法,这个方法的实现也很简单,遍历Routes向一个实现了IRouter接口的RouteCollection对象添加IRouter,我们可以先看一下RouteCollection的实现:
public class RouteCollection : IRouteCollection
{
private readonly List<IRouter> _routes = new List<IRouter>();
private readonly List<IRouter> _unnamedRoutes = new List<IRouter>();
private readonly Dictionary<string, INamedRouter> _namedRoutes =
new Dictionary<string, INamedRouter>(StringComparer.OrdinalIgnoreCase); private RouteOptions _options; public IRouter this[int index]
{
get { return _routes[index]; }
} public int Count
{
get { return _routes.Count; }
} public void Add([NotNull] IRouter router)
{
var namedRouter = router as INamedRouter;
if (namedRouter != null)
{
if (!string.IsNullOrEmpty(namedRouter.Name))
{
_namedRoutes.Add(namedRouter.Name, namedRouter);
}
}
else
{
_unnamedRoutes.Add(router);
} _routes.Add(router);
} public async virtual Task RouteAsync(RouteContext context)
{
for (var i = ; i < Count; i++)
{
var route = this[i]; var oldRouteData = context.RouteData; var newRouteData = new RouteData(oldRouteData);
newRouteData.Routers.Add(route); try
{
context.RouteData = newRouteData; await route.RouteAsync(context);
if (context.IsHandled)
{
break;
}
}
finally
{
if (!context.IsHandled)
{
context.RouteData = oldRouteData;
}
}
}
} public virtual VirtualPathData GetVirtualPath(VirtualPathContext context)
{
EnsureOptions(context.Context); // If we're using Best-Effort link generation then it means that we'll first look for a route where
// the route values are validated (context.IsBound == true). If we can't find a match like that, then
// we'll return the path from the first route to return one.
var useBestEffort = _options.UseBestEffortLinkGeneration; if (!string.IsNullOrEmpty(context.RouteName))
{
var isValidated = false;
VirtualPathData bestPathData = null;
INamedRouter matchedNamedRoute;
if (_namedRoutes.TryGetValue(context.RouteName, out matchedNamedRoute))
{
bestPathData = matchedNamedRoute.GetVirtualPath(context);
isValidated = context.IsBound;
} // If we get here and context.IsBound == true, then we know we have a match, we want to keep
// iterating to see if we have multiple matches.
foreach (var unnamedRoute in _unnamedRoutes)
{
// reset because we're sharing the context
context.IsBound = false; var pathData = unnamedRoute.GetVirtualPath(context);
if (pathData == null)
{
continue;
} if (bestPathData != null)
{
// There was already a previous route which matched the name.
throw new InvalidOperationException(
Resources.FormatNamedRoutes_AmbiguousRoutesFound(context.RouteName));
}
else if (context.IsBound)
{
// This is the first 'validated' match that we've found.
bestPathData = pathData;
isValidated = true;
}
else
{
Debug.Assert(bestPathData == null); // This is the first 'unvalidated' match that we've found.
bestPathData = pathData;
isValidated = false;
}
} if (isValidated || useBestEffort)
{
context.IsBound = isValidated; if (bestPathData != null)
{
bestPathData = new VirtualPathData(
bestPathData.Router,
NormalizeVirtualPath(bestPathData.VirtualPath),
bestPathData.DataTokens);
} return bestPathData;
}
else
{
return null;
}
}
else
{
VirtualPathData bestPathData = null;
for (var i = ; i < Count; i++)
{
var route = this[i]; var pathData = route.GetVirtualPath(context);
if (pathData == null)
{
continue;
} if (context.IsBound)
{
// This route has validated route values, short circuit.
return new VirtualPathData(
pathData.Router,
NormalizeVirtualPath(pathData.VirtualPath),
pathData.DataTokens);
}
else if (bestPathData == null)
{
// The values aren't validated, but this is the best we've seen so far
bestPathData = pathData;
}
} if (useBestEffort)
{
return new VirtualPathData(
bestPathData.Router,
NormalizeVirtualPath(bestPathData.VirtualPath),
bestPathData.DataTokens);
}
else
{
return null;
}
}
} private PathString NormalizeVirtualPath(PathString path)
{
var url = path.Value; if (!string.IsNullOrEmpty(url) && _options.LowercaseUrls)
{
var indexOfSeparator = url.IndexOfAny(new char[] { '?', '#' }); // No query string, lowercase the url
if (indexOfSeparator == -)
{
url = url.ToLowerInvariant();
}
else
{
var lowercaseUrl = url.Substring(, indexOfSeparator).ToLowerInvariant();
var queryString = url.Substring(indexOfSeparator); // queryString will contain the delimiter ? or # as the first character, so it's safe to append.
url = lowercaseUrl + queryString;
} return new PathString(url);
} return path;
} private void EnsureOptions(HttpContext context)
{
if (_options == null)
{
_options = context.RequestServices.GetRequiredService<IOptions<RouteOptions>>().Options;
}
}
}
乍一看这个类的功能还是比较庞大的,我们主要关注他对IRouter接口签名的实现:
Task RouteAsync(RouteContext context):
通过代码我们可以看到,这个方法主要对RouteCollection本身持有的Route 规则循环添加到路由上下文RouteContext.RouteData中。
VirtualPathData GetVirtualPath(VirtualPathContext context):
ASP.NET MVC 源码分析(二) —— 从 IRouteBuilder认识路由构建的更多相关文章
- asp.net mvc源码分析-ModelValidatorProviders 客户端的验证
几年写过asp.net mvc源码分析-ModelValidatorProviders 当时主要是考虑mvc的流程对,客户端的验证也只是简单的提及了一下,现在我们来仔细看一下客户端的验证. 如图所示, ...
- ASP.NET MVC源码分析
MVC4 源码分析(Visual studio 2012/2013) HttpModule中重要的UrlRoutingModule 9:this.OnApplicationPostResolveReq ...
- asp.net mvc源码分析-DefaultModelBinder 自定义的普通数据类型的绑定和验证
原文:asp.net mvc源码分析-DefaultModelBinder 自定义的普通数据类型的绑定和验证 在前面的文章中我们曾经涉及到ControllerActionInvoker类GetPara ...
- ASP.NET MVC 源码分析(一)
ASP.NET MVC 源码分析(一) 直接上图: 我们先来看Core的设计: 从项目结构来看,asp.net.mvc.core有以下目录: ActionConstraints:action限制相关 ...
- asp.net MVC 源码分析
先上一张图吧 asp.net请求机制的图 by传智播客邹华栋老师 然后是 邹老师添加MVC请求过程的图 其实MVC 是在.netframework上加了一个过滤器 HttpModule 在C:\W ...
- asp.net mvc源码分析-Route的GetRouteData
我知道Route这里东西应该算路由,这里把它放到mvc里面有些不怎么合适,但是我想大家多数遇到路由都是在mvc的时候吧.首先我们还是来看看GetRouteData方法吧 [csharp] public ...
- asp.net mvc源码分析-Action篇 IModelBinder
我们首先还是看看ReflectedParameterBindingInfo的Binder属性吧: public override IModelBinder Binder { ge ...
- ASP.NET MVC源码分析系列
Controller下的JsonResult的ExecuteResult方法 public override void ExecuteResult(ControllerContext context) ...
- ASP.NET WebForm / MVC 源码分析
浏览器 Url:https//localhost:6565/Home/Index ,https//localhost:6565/WebForm1.aspx,请求服务器(构建请求报文,并且将请求报文发送 ...
随机推荐
- Decode the Strings
http://acm.hdu.edu.cn/showproblem.php?pid=2371 题意:给出一个长度为n的字符串(标号为1~n),以及n个数代表字符串的变换规则,问该字符串是由哪个字符串按 ...
- bzoj1992鬼谷子的钱袋(二分乱搞 二进制)
1192: [HNOI2006]鬼谷子的钱袋 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 3223 Solved: 2333 Descriptio ...
- AirtestIDE详解(跨平台的UI自动化编辑器)
Airtest 是网易出品的一款基于图像识别和poco控件识别的一款UI自动化测试工具. AirtestIDE 是一个跨平台.多端(Windows.web.android.ios.游戏)的UI自动化测 ...
- MySQL数据库笔记总结
MySQL数据库总结 一.数据库简介 1. 数据 所谓数据(Data)是指对客观事物进行描述并可以鉴别的符号,这些符号是可识别的.抽象的.它不仅仅指狭义上的数字,而是有多种表现形式:字母.文字.文本. ...
- 微信小程序上传多张图片,及php后台处理
微信小程序上传多张图片,级小程序页面布局直接来代码index.wxml <view class='body' style='width:{{windowWidth}}px;height:{{wi ...
- 微信小程序调用微信支付
1,首先我们先缕清支付的整个流程,详见https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_4&index=3,第一 ...
- Objective-C copy(转)
一.从面向对象到Objective-C概览copy 1.面向对象: In object-oriented programming, object copying is creating a copy ...
- ACM_招新笔试题系列——买包子
招新笔试题系列——买包子 Time Limit: 2000/1000ms (Java/Others) Problem Description: 小华刚到大学,一天早上她替她室友买早餐,一共要N个包子. ...
- Docker学习系列(一):windows下安装docker(转载)
本文目录如下: windows按照docker的基本要求 具体安装步骤 开始使用 安装远程连接工具连接docker 安装中遇到的问题 Docker的更新 Docker中的jupyter windows ...
- 记Spring下autowire为name时的一个现象
当autowire为byname时,假如有一个名为“user”的component,恰巧还有另一个属性为“user”,它的set方法为setUser(User user),Spring会强行把comp ...