【发布时间】:2021-06-23 06:47:07
【问题描述】:
我有一个 .net core 3.1 api,我想对我的控制器进行版本控制,我认为服务层的版本控制结构如下所示
public interface IVersionableObject { }
public class GetDataV1 : IVersionableObject { }
public class PostDataV1 : IVersionableObject { }
public class GetDataV2 : IVersionableObject { }
public class PostDataV2 : IVersionableObject { }
public class ListItemV1 : IVersionableObject { }
public class MobileAppServiceV1
{
public virtual async Task<IVersionableObject> Get()
{
return new GetDataV1();
}
public virtual async Task<IVersionableObject> Post()
{
return new PostDataV1();
}
public virtual async Task<IVersionableObject> ListItems()
{
return new ListItemV1();
}
}
public class MobileAppServiceV2 : MobileAppServiceV1
{
public override async Task<IVersionableObject> Get()
{
return new GetDataV2();
}
public override async Task<IVersionableObject> Post()
{
return new PostDataV2();
}
[Obsolete("This method is not available for after V1" , true)]
public async Task<IVersionableObject> ListItems()
{
throw new NotSupportedException("This method is not available for after V1");
}
}
让我们检查控制器
V1 控制器
[ApiVersion("1.0")]
[Route("api/{v:apiVersion}/values")]
public class ValuesControllerV1 : ControllerBase
{
private readonly MobileAppServiceV1 _mobileAppServiceV1;
public ValuesControllerV1()
{
_mobileAppServiceV1 = new MobileAppServiceV1();
}
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok(await _mobileAppServiceV1.Get());
}
[HttpGet("listItem")]
public async Task<IActionResult> ListItems()
{
return Ok(await _mobileAppServiceV1.ListItems());
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] string value)
{
return Ok(await _mobileAppServiceV1.Post());
}
}
V2 控制器
[ApiVersion("2.0")]
[Route("api/{v:apiVersion}/values")]
public class ValuesControllerV2 : ControllerBase
{
private readonly MobileAppServiceV2 _mobileAppServiceV2;
public ValuesControllerV2()
{
_mobileAppServiceV2 = new MobileAppServiceV2();
}
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok(await _mobileAppServiceV2.Get());
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] string value)
{
return Ok(await _mobileAppServiceV2.Post());
}
}
例如在 v2 上移除 ListItems 方法,我避免在 v2 上使用带有 Obselete 属性的 ListItem 方法。
最后我想到了这样的结构,我尝试用示例代码来展示它。你能给出一些关于这是好的结构还是不适合 web api 上的版本控制服务层的想法?我愿意接受所有建议。
【问题讨论】:
标签: c# api inheritance versioning api-versioning