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,请求服务器(构建请求报文,并且将请求报文发送 ...
随机推荐
- sort与sorted的区别
描述 我们需要对List进行排序,Python提供了两个方法对给定的List L进行排序 : 方法1.用对List的成员函数sort进行排序 方法2.用内置函数sorte ...
- ural 1017. Staircases(dp)
http://acm.timus.ru/problem.aspx?space=1&num=1017 题意:有n块砖,要求按照严格递增的个数摆放成楼梯,求楼梯的摆放种类数. 思路:状态转移方程: ...
- BZOJ 4310 二分+SA+RMQ
思路: 首先求出后缀数组和height数组,这样能得到本质不同的子串数目 这里利用:本质不同的子串=∑(Len−SA[i]−height[i])=∑(Len−SA[i]−height[i])利用SA[ ...
- Linux下查看CPU和内存(很详细)
在系统维护的过程中,随时可能有需要查看 CPU 使用率,并根据相应信息分析系统状况的需要.在 CentOS 中,可以通过 top 命令来查看 CPU 使用状况.运行 top 命令后,CPU 使用状态会 ...
- Linux-fork()函数详解,附代码注释
// // main.c // Project_C // // Created by LiJinxu on 16/8/13. // Copyright © 2016年 LiJinxu-NEU. All ...
- 【转】Linux下history命令用法
转自:http://blog.sina.com.cn/s/blog_5caa94a00100gyls.html 如果你经常使用 Linux 命令行,那么使用 history(历史)命令可以有效地提升你 ...
- [转]java处理高并发高负载类网站的优化方法
本文转自:http://www.cnblogs.com/pengyongjun/p/3406210.html java处理高并发高负载类网站中数据库的设计方法(java教程,java处理大量数据,ja ...
- Android 微信SDK图片分享(checkArgs fail, thumbData is invalid)
微信官网给的Demo中.图片的分享例子他是这么描述的: String url = "http://pic2.nipic.com/20090506/1478953_125254084_2.jp ...
- Leetcode0523--Continuous Subarray Sum 连续和倍数
[转载请注明]https://www.cnblogs.com/igoslly/p/9341666.html class Solution { public: bool checkSubarraySum ...
- 解决sql server死锁
-- 查询死锁 select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName from sys ...