在ASP NET Web API中进行路由-适用于API的不同版本 [英] Routing in ASP NET Web API - For different versions of an API

查看:82
本文介绍了在ASP NET Web API中进行路由-适用于API的不同版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从属性路由 api-routing-and-actions / attribute-routing-in-web-api-2 rel = noreferrer>此处

I am reading about Attribute Routing in Web API 2 from here

文章说,

Here are some other patterns that attribute routing makes easy.

API versioning

In this example, "/api/v1/products" would be routed to a different controller than "/api/v2/products".

/api/v1/products
/api/v2/products

为什么?

编辑:我会在 常规路由中进行此操作:

I would do this in Normal Routing:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
         config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/v2/products",
            defaults: new { controller = V2_Products }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/v1/products",
            defaults: new { controller = V1_Products }
        );
    }
}

有人可以在属性路由的方式?对于本示例,使用属性路由如何变得更容易和方便(根据文章)?

Could anyone explain me how to do this in Attribute Routing way ? And how come using Attribute routing is easier and convenient for this example (according to the article) ?

推荐答案

有很多方法可以通过属性路由来实现版本控制;一种非常基本的方法是使用每个ApiController版本的RoutePrefix 属性

There are many ways to implement versionning with attribute routing ; A really basic way is to use RoutePrefix attribute for each version of your ApiController

[RoutePrefix("v1")]
public class V1_ProductsController : ApiController
{
    [Route("products")]
    public IEnumerable<string> Get()
    {
        return new string[] { "v1-product1", "v1-product2" };
    }
     //....
}


[RoutePrefix("v2")]
public class V2_ProductsController : ApiController
{
     [Route("products")]
    public IEnumerable<string> Get()
    {
        return new string[] { "v2-product1", "v2-product2" };
    }
    //....
}

/ v1 /产品转到第一个版本的 / v2 / products 进入第二个版本。

/v1/products goes to the first version of /v2/products goes to the second one.

这篇关于在ASP NET Web API中进行路由-适用于API的不同版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆