如何在.net Core中执行api版本控制?

时间:2019-03-29 14:30:00

标签: c# .net asp.net-core

我已经编写了如下所示的控制器(.net core 2.1):

[ApiVersion("1")]
[Consumes("application/json")]
[Produces("application/json")]
[Route("v{version:apiVersion}/[controller]")]
public class AccountController : ControllerBase
{
    // GET: api/Account
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

我正在以这种方式调用上面的控制器(大招):

curl -X GET "https://localhost:44363/v1/Account" -H "accept: application/json"

但是我仍然收到如下所示的404错误。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /v1/Account</pre>
</body>
</html>

不确定我在做什么错。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您不需要提供这样的路由,因为api版本控制系统已经知道了。

首先,您应该配置api版本控制,例如:

public void ConfigureServices( IServiceCollection services )
{
    services.AddMvc();
    services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));

    //and the rest
}

然后进行简单配置:

services.AddApiVersioning(
    o =>
    {
        o.AssumeDefaultVersionWhenUnspecified = true );
        o.DefaultApiVersion = new ApiVersion( 1 );
    } );

这将创建默认的api版本,并假设如果请求中未指定任何版本,则将考虑默认的版本。

接下来,您的控制器应如下所示:

[ApiVersion( "1" )]
[Route( "api/mystuff" )]
public class mystuff1: Controller 
{
    [HttpGet]
    public string Get() => "Mystuff1!";
}


[ApiVersion( "2" )]
[Route( "api/mystuff" )]
public class mystuff2 : Controller 
{
    [HttpGet]
    public string Get() => "Mystuff2!";
}

然后将标头添加到您的请求中: api版本:2

(这是通过ConfigureServices中的AddApiVersioning完成的。)