如何让NSwag生成返回Task<ActionResult>的控制器而非Task<MyDTO>?
让NSwag openapi2cscontroller生成返回Task<ActionResult>的控制器方法
我在用NSwag的openapi2cscontroller工具生成ASP.NET Core控制器时,希望方法返回类型为Task<ActionResult<ProductResponseDto>>,而非当前的Task<ProductResponseDto>。当前返回类型无法在出错时返回ErrorDto,我知晓可以通过抛出异常并配合中间件处理,但希望找到不依赖异常的解决方案。
我的Swagger定义
paths: '/Products/{id}': get: tags: - Products operationId: getProductById parameters: - name: id in: path required: true schema: type: string responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ProductResponseDto' '404': description: Entity not found content: application/json: schema: $ref: '#/components/schemas/ErrorDto'
当前生成的接口
/// <returns>Success</returns> System.Threading.Tasks.Task<ProductResponseDto> GetProductByIdAsync(string id);
我的csproj配置
<Target Name="GenerateControllers" BeforeTargets="PrepareForBuild"> <Copy SourceFiles="@(Reference)" DestinationFolder="$(OutDir)References" /> <Exec Command="$(NSwagExe_Net80) openapi2cscontroller /input:./product_openapi.yaml /classname:Products /namespace:AspNetCore.Examples.ProductService.Controllers /output:obj/ProductsController.cs /ControllerBaseClass:Microsoft.AspNetCore.Mvc.ControllerBase" /> <ItemGroup> <Compile Include="obj/ProductsController.cs" Exclude="@(Compile)" /> </ItemGroup> </Target>
解决方案
在NSwag的openapi2cscontroller命令中添加/operationResultType:ActionResult参数,该参数会让生成的控制器方法返回Task<ActionResult<T>>类型,从而支持在实现中返回不同状态码对应的结果(比如Ok()或NotFound())。
修改后的Exec命令如下:
<Exec Command="$(NSwagExe_Net80) openapi2cscontroller /input:./product_openapi.yaml /classname:Products /namespace:AspNetCore.Examples.ProductService.Controllers /output:obj/ProductsController.cs /ControllerBaseClass:Microsoft.AspNetCore.Mvc.ControllerBase /operationResultType:ActionResult" />
执行修改后的命令后,生成的接口会变为:
/// <returns>Success</returns> System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.ActionResult<ProductResponseDto>> GetProductByIdAsync(string id);
此时你就可以在控制器实现中直接返回Ok(productResponseDto)或者NotFound(errorDto),无需依赖异常处理。
内容的提问来源于stack exchange,提问作者ddfra
相关产品推荐
相关产品推荐

