Asp.net WebForm Web API版本处理使用命名空间和持久的旧API

时间:2015-09-25 09:25:26

标签: c# asp.net asp.net-web-api2

我有一个包含Web Api v2的asp.net WebForm项目。我没有考虑api版本,并在下面用简单的路线添加我的整个api:

RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);

但是,现在,我需要创建版本控制,因为我有很多变化,并且不想让使用旧api的旧客户端失望。所以我创建了一个名为APIv2的新文件夹并在那里创建了我的控制器(它与旧的api同名)。问题是如何路由这样的东西:

MyWebsite/API/Item => For ItemController OF OLD API
MyWebsite/APIv2/Item => For ItemController Of New API (Version 2)

我看了很多帖子,但没有一个对我有用!我也创建了NamespaceHttpControllerSelector,但它也不起作用。

请给我一些如何处理这个问题的例子。

P.S:当我为新api创建简单路由(如旧路由)时,它表示找到了重复控制器! (虽然我使用不同的命名空间)

编辑(添加我的完整代码):

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration));

        RouteTable.Routes.MapHttpRoute(
        name: "VersionedApi",
        routeTemplate: "api/v2/{controller}");

        RouteTable.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}");

和NamespaceHttpControllerSelector:

public class NamespaceHttpControllerSelector : DefaultHttpControllerSelector
{
    private const string ControllerKey = "controller";
    private readonly HttpConfiguration _configuration;
    private readonly Lazy<IEnumerable<Type>> _duplicateControllerTypes;

    public NamespaceHttpControllerSelector(HttpConfiguration configuration) : base(configuration)
    {
        _configuration = configuration;
        _duplicateControllerTypes = new Lazy<IEnumerable<Type>>(GetDuplicateControllerTypes);
    }

    public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
    {
        var routeData = request.GetRouteData();
        if (routeData == null || routeData.Route == null || routeData.Route.DataTokens == null || routeData.Route.DataTokens["Namespaces"] == null) 
            return base.SelectController(request);

        // Look up controller in route data
        object controllerName;
        routeData.Values.TryGetValue(ControllerKey, out controllerName);
        var controllerNameAsString = controllerName as string;
        if (controllerNameAsString == null) 
            return base.SelectController(request);

        //get the currently cached default controllers - this will not contain duplicate controllers found so if
        // this controller is found in the underlying cache we don't need to do anything
        var map = base.GetControllerMapping();
        if (map.ContainsKey(controllerNameAsString)) 
            return base.SelectController(request);

        //the cache does not contain this controller because it's most likely a duplicate, 
        // so we need to sort this out ourselves and we can only do that if the namespace token
        // is formatted correctly.
        var namespaces = routeData.Route.DataTokens["Namespaces"] as IEnumerable<string>;
        if (namespaces == null)
            return base.SelectController(request);

        //see if this is in our cache
        var found = _duplicateControllerTypes.Value
            .Where(x => string.Equals(x.Name, controllerNameAsString + ControllerSuffix, StringComparison.OrdinalIgnoreCase))
            .FirstOrDefault(x => namespaces.Contains(x.Namespace));

        if (found == null)
            return base.SelectController(request);

        return new HttpControllerDescriptor(_configuration, controllerNameAsString, found);
    }

    private IEnumerable<Type> GetDuplicateControllerTypes()
    {
        var assembliesResolver = _configuration.Services.GetAssembliesResolver();
        var controllersResolver = _configuration.Services.GetHttpControllerTypeResolver();
        var controllerTypes = controllersResolver.GetControllerTypes(assembliesResolver);

        //we have all controller types, so just store the ones with duplicate class names - we don't
        // want to cache too much and the underlying selector caches everything else

        var duplicates = controllerTypes.GroupBy(x => x.Name)
            .Where(x => x.Count() > 1)
            .SelectMany(x => x)
            .ToArray();

        return duplicates;
    }

}

2 个答案:

答案 0 :(得分:1)

您可以使用Web Api属性路由。

public ItemControllerV2 : ApiController
{
    [Route("v2/item/{id:int}")]
    public Item Get(int id)
    {
        ....
    }
}

还要记住在Web Api配置中启用属性路由

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        //rest of your Web Api configuration
    }
 }

有关属性路由的更多信息,请访问:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

修改

如果您在评论中写道,您在控制器中有很多方法,并且您不想为每个可以使用RoutePrefix属性的方法添加属性:

[RoutePrefix("v2/item")]
public ItemControllerV2 : ApiController
{
}
  

另外,我没有WebApiConfig文件,我应该在哪里创建它?

它与您进行方法调用的位置相同:

RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);

因此,在这个地方你必须添加以下方法调用来启用属性路由:

GlobalConfiguration.Configure(config => 
{
    config.MapHttpAttributeRoutes();

    RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}"
    );
});

答案 1 :(得分:1)

仅添加NamespaceHttpControllerSelector是不够的,您必须为其提供数据。

这一行

var namespaces = routeData.Route.DataTokens["Namespaces"] as IEnumerable<string>;

告诉它需要一个名称空间列表来查找名为&#34; Namespaces&#34;的数据令牌中的控制器。但问题是,在WebAPI中设置DataTokens并不容易(它们最初来自MVC),因此我们必须更改代码。

替换

//the cache does not contain this controller because it's most likely a duplicate, 
// so we need to sort this out ourselves and we can only do that if the namespace token
// is formatted correctly.
var namespaces = routeData.Route.DataTokens["Namespaces"] as IEnumerable<string>;
if (namespaces == null)
  return base.SelectController(request);

//see if this is in our cache
var found = _duplicateControllerTypes.Value
  .Where(x => string.Equals(x.Name, controllerNameAsString + ControllerSuffix, StringComparison.OrdinalIgnoreCase))
  .FirstOrDefault(x => namespaces.Contains(x.Namespace));

var @namespace = routeData.Values["namespace"] as string;
if (@namespace == null)
  return base.SelectController(request);

//see if this is in our cache
var found = _duplicateControllerTypes.Value
  .Where(x => string.Equals(x.Name, controllerNameAsString + ControllerSuffix, StringComparison.OrdinalIgnoreCase))
  .FirstOrDefault(x => x.Namespace == @namespace);

按如下方式更改路线:

RouteTable.Routes.MapHttpRoute(
  name: "VersionedApi",
  routeTemplate: "api/v2/{controller}",
  defaults: new {@namespace = "your namespace for v2 controllers"}
);

RouteTable.Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}",
  defaults: new {@namespace = "your namespace for v1 controllers"}
);