·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> 解读ASP.NET 5 & MVC6系列(12):基于Lamda表达式的强类型Routing实现

解读ASP.NET 5 & MVC6系列(12):基于Lamda表达式的强类型Routing实现

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

解读asp.net 5 & MVC6系列(12):基于Lamda表达式的强类型Routing实现

2015-05-27 09:05 by 汤姆大叔, ... 阅读, ... 评论, 收藏, 编辑

前面的深入理解Routing章节,我们讲到了在MVC中,除了使用默认的ASP.NET 5的路由注册方式,还可以使用基于Attribute的特性(Route和HttpXXX系列方法)来定义。本章,我们将讲述一种基于Lambda表达式的强类型类型。

这种方式的基本使用示例如下:

services.Configure<MvcOptions>(opt =>{    opt.EnableTypedRouting();    opt.GetRoute("homepage", c => c.Action<PRoductsController>(x => x.Index()));    opt.GetRoute("aboutpage/{name}", c => c.Action<ProductsController>(x => x.About(Param<string>.Any)));    opt.PostRoute("sendcontact", c => c.Action<ProductsController>(x => x.Contact()));});

从示例中可以看出,我们可以通过GetRoute或PostRoute等扩展方法来定义route,而且后面使用Lambda表达式来定Controller的类型和Action的方法。

注意,在这里获取Action的方法名,是通过委托执行该Action方法来实现的(实际上并没有执行,而是基于此获取该Action的MethodInfo)。

实现原理

Stratup.csConfigureServices方法中配置services的时候,我们可以对MVC站点使用的核心配置文件MvcOptions进行配置,其中该类有一个applicationModelConventions属性(List<IApplicationModelConvention>)可以保存一个IApplicationModelConvention接口的集合,改接口可以对MVC程序的程序模型进行管线处理,该接口的定义如下:

public interface IApplicationModelConvention{   void Apply(ApplicationModel application);}

接口中的Apply方法所接收的参数类型是ApplicationModel,而ApplicationModel有两个极其重要的内容可以供我们操作,一个是Controller模型集合,一个是各种Filter的集合,该类的定义如下:

public class ApplicationModel{    public ApplicationModel();    public IList<ControllerModel> Controllers { get; }    public IList<IFilter> Filters { get; }}

这里最重要的就是ControllerModel类,该类的实例上保存了各种各样重要而又可以操作的信息,比如该类和相关Action上的路由定义数据,API描述信息,路由约束等等,这些信息都可以进行操作。

新的IApplicationModelConvention注册方式如下:

services.Configure<MvcOptions>(opt =>{   opts.ApplicationModelConventions.Add(new MyApplicationModelConvention());});

所以我们可以利用这个方法,在合适的时机对整个MVC的程序模型做响应的调整和修改,本章节中的强类型路由就是利用这个特性来实现的。

实现步骤

首先定义一个强类型的路由模型TypedRouteModel类,该类要继承于AttributeRouteModelAttributeRouteModel类是基于Attribute路由的基本模型,TypedRouteModel类的代码如下:

public class TypedRouteModel : AttributeRouteModel{    public TypedRouteModel(string template)    {        Template = template;        HttpMethods = new string[0];    }    public TypeInfo ControllerType { get; private set; }    public MethodInfo ActionMember { get; private set; }    public IEnumerable<string> HttpMethods { get; private set; }    public TypedRouteModel Controller<TController>()    {        ControllerType = typeof(TController).GetTypeInfo();        return this;    }    public TypedRouteModel Action<T, U>(Expression<Func<T, U>> expression)    {        ActionMember = GetMethodInfoInternal(expression);        ControllerType = ActionMember.DeclaringType.GetTypeInfo();        return this;    }    public TypedRouteModel Action<T>(Expression<Action<T>> expression)    {        ActionMember = GetMethodInfoInternal(expression);        ControllerType = ActionMember.DeclaringType.GetTypeInfo();        return this;    }    private static MethodInfo GetMethodInfoInternal(dynamic expression)    {        var method = expression.Body as MethodCallExpression;        if (method != null)            return method.Method;        throw new ArgumentException("Expression is incorrect!");    }    public TypedRouteModel WithName(string name)    {        Name = name;        return this;    }    public TypedRouteModel ForHttpMethods(params string[] methods)    {        HttpMethods = methods;        return this;    }}

该类主要的功能是:定义支持传入Controller类型,支持链式调用。

然后再定义一个继承IApplicationModelConvention接口的TypedRoutingApplicationModelConvention类。代码如下:

public class TypedRoutingApplicationModelConvention : IApplicationModelConvention{    internal static readonly Dictionary<TypeInfo, List<TypedRouteModel>> Routes = new Dictionary<TypeInfo, List<TypedRouteModel>>();    public void Apply(ApplicationModel application)    {        foreach (var controller in application.Controllers)        {            if (Routes.ContainsKey(controller.ControllerType))            {                var typedRoutes = Routes[controller.ControllerType];                foreach (var route in typedRoutes)                {                    var action = controller.Actions.FirstOrDefault(x => x.ActionMethod == route.ActionMember);                    if (action != null)                    {                        action.AttributeRouteModel = route;                        //注意这里是直接替换,会影响现有Controller上的Route特性定义的路由                        foreach (var method in route.HttpMethods)                        {                            action.HttpMethods.Add(method);                        }                    }                }            }        }    }}

在该类中,保存了一个静态变量Routes,用于保存所有以Lamda表达式方式声明的路由,然后在现有的Controllers集合中进行查找及修改,然后替换AttributeRouteModel属性,并设置响应的Http Method(如果不设置,则默认所有的方式都允许)。

在这里,我们只是简单替换action.AttributeRouteModel,所以会导致一些缺陷(比如一个Action只能支持一个路由路径,以最后一个为准),各位同学可以根据自己的能力进行优化。

优化的时候,要注意Controller上的Route集合保存在controller.Attributes属性上,Action上的Route集合保存在action.Attributes属性上,可以对其进行优化。

然后,在MvcOptions上,我们再为TypeRouteModel添加一些扩展方法以方便使用,代码如下:

public static class MvcOptionsExtensions{    public static TypedRouteModel GetRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup)    {        return AddRoute(template, configSetup).ForHttpMethods("GET");    }    public static TypedRouteModel PostRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup)    {        return AddRoute(template, configSetup).ForHttpMethods("POST");    }    public static TypedRouteModel PutRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup)    {        return AddRoute(template, configSetup).ForHttpMethods("PUT");    }    public static TypedRouteModel DeleteRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup)    {        return AddRoute(template, configSetup).ForHttpMethods("DELETE");    }    public static TypedRouteModel TypedRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup)    {        return AddRoute(template, configSetup);    }    private static TypedRouteModel AddRoute(string template, Action<TypedRouteModel> configSetup)    {        var route = new TypedRouteModel(template);        configSetup(route);        if (TypedRoutingApplicationModelConvention.Routes.ContainsKey(route.ControllerType))        {            var controllerActions = TypedRoutingApplicationModelConvention.Routes[route.ControllerType];            controllerActions.Add(route);        }        else        {            var controllerActions = new List<TypedRouteModel> { route };            TypedRoutingApplicationModelConvention.Routes.Add(route.ControllerType, controllerActions);        }        return route;    }    public static void EnableTypedRouting(this MvcOptions opts)    {        opts.ApplicationModelConventions.Add(new TypedRoutingApplicationModelConvention());    }}

在上述代码中,我们添加了一个EnableTypedRouting扩展方法,以便向MvcOptions.ApplicationModelConventions属性上添加新的TypedRoutingApplicationModelConvention类型示例。

其它的扩展方法则都是用于声明相关的route,大家注意,在最开头的示例中,我们看到获取action信息的方法是通过委托调用该action方法(但没有真正调用),但是有的方法有参数,那怎么办呢?为此,我们定于一个忽略参数的Param类,代码如下:

public static class Param<TValue>{    public static TValue Any    {        get { return default(TValue); }    }}

这样,我们为含有参数的About方法定于路由的时候,就可以这样来定义了,代码如下:

						
  • 上一篇文章:
  • 下一篇文章: