defaults: new { id = RouteParameter.Optional });config.Servi

时间:2022-02-26 08:38:31

版本控制的要领有很多,这里供给一种将Odata与普通web api版本控制机制统一的要领,但也可以单独控制,整合控制与单独控制主要的差别是:整合控制通过VersionControllerSelector来选择控制器过滤器,而不是直接选择控制器。

给与此机制来控制版本,应凭据如下法则定名控制器:

自界说标识符+版本+Controller

自界说标识符:能浮现控制器含义的字符串

版本:暗示版本的字符串,例如:V1,V1.0;不建议使用V1.0这样的写法,因为这样控制器名称会相当怪异,如果暗示小版本号,那么可以使用V1D0,这种写法,即用一个字母取代句号。

定名空间对应了项目文件的组织形式,控制器的定名空间为:

defaults: new { id = RouteParameter.Optional });config.Servi

1 Odata版本控制

扩展DefaultHttpControllerSelector

public class ODataVersionControllerSelector : DefaultHttpControllerSelector { public Dictionary<string, string> RouteVersionSuffixMapping { get; set; } public ODataVersionControllerSelector(HttpConfiguration configuration) : base(configuration) { if (RouteVersionSuffixMapping == null) { RouteVersionSuffixMapping = new Dictionary<string, string>(); } } public override string GetControllerName(HttpRequestMessage request) { var controllerName = base.GetControllerName(request); if (string.IsNullOrEmpty(controllerName)) { return controllerName; } var routeName = request.ODataProperties().RouteName; if (string.IsNullOrEmpty(routeName)) { return controllerName; } var mapping = GetControllerMapping(); if (!RouteVersionSuffixMapping.ContainsKey(routeName)) { return controllerName; } var versionControllerName = controllerName + RouteVersionSuffixMapping[routeName]; return mapping.ContainsKey(versionControllerName) ? versionControllerName : controllerName; } }

改削WebApiConfig.Register要领

public static class WebApiConfig {   public static void Register(HttpConfiguration config)   {       ......       //odata路由 config.MapODataServiceRoute( routeName: "V1OdataRouteVersioning", routePrefix: "Odata/V1", model: GetEdmModel()); config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); config.AddODataQueryFilter(); config.Services.WordStr(typeof(IHttpControllerSelector), new ODataVersionControllerSelector (config)); var controllerSelector = config.Services.GetService(typeof(IHttpControllerSelector)) as ODataVersionControllerSelector ;        controllerSelector.RouteVersionSuffixMapping.Add("V1OdataRouteVersioning", "V1");         ......   } } private static IEdmModel GetEdmModel() {   ODataConventionModelBuilder builder = new ODataConventionModelBuilder();   #region Publication   var publicationsSet = builder.EntitySet<Publication>("Publications").EntityType.Collection;   var getPublicationsFunction = publicationsSet.Function("GetPublications").Returns<PublicationDTO>();   getPublicationsFunction.Parameter<int>("userId"); publicationsSet.Action("AddPublication").Returns<int>().Parameter<PublicationAddBindingModel>("publicationAddBM");   publicationsSet.Action("DeletePublication").Returns<IHttpActionResult>().Parameter<PublicationDelBindingModel>("publicationDelBM"); #endregion   builder.Namespace = "Service";   return builder.GetEdmModel(); }

2 普通Api版本控制

扩展IHttpControllerSelector