首页 > 解决方案 > 具有招摇属性的 CreatedAtRouteResult

问题描述

我有 asp.net 核心 web api。我的一个控制器返回 CreatedAtRouteResult。如何为此方法添加 swagger 属性。

[HttpPost]
[SwaggerResponse(400, typeof(NotFoundResult))]
[SwaggerResponse(201, typeof(CreatedAtRouteResult))]
public async Task<IActionResult> Create([FromBody] SubscriptionDTO dto)
{
    var issuedTo = (await _tokenService.Get()).IssuedTo;
    SubscriptionDresult = await _subscriptionService.CreateAsync(dto, issuedTo.Id);
    return result == null ? (IActionResult)NotFound(): CreatedAtRoute(new {id = result.Id}, result);
}

有人可以解释如何设置这种类型的招摇响应属性吗?

标签: asp.net-coreattributesswaggerasp.net-core-webapi

解决方案


如果您ProduceResponseType在方法上使用属性,swagger 会自动将其拾取并将其添加到 swagger.json 文档中。

[HttpPost]
[ProducesResponseType(typeof(SubscriptionDTO), (int)HttpStatusCode.Created)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Create([FromBody] SubscriptionDTO dto)
{
    var issuedTo = (await _tokenService.Get()).IssuedTo;
    SubscriptionDTO result = await _subscriptionService.CreateAsync(dto, issuedTo.Id);
    return result == null ? (IActionResult)NotFound(): CreatedAtRoute(new {id = result.Id}, result);
}

请注意,您需要指定为每个响应代码返回的实际 DTO 类型ProduceResponseType。用于void无返回体。


推荐阅读