asp.net NSwag无法创建继承控制器的Swagger

xpcnnkqh  于 12个月前  发布在  .NET
关注(0)|答案(2)|浏览(173)

在我的ASP.NET Core应用程序中,我使用NSwag创建swagger.json文件。
当我构建我的项目时,我得到以下错误:
严重性代码描述项目文件行抑制状态错误MSB 3073命令“dotnet“. nuget\packages\nswag.msbuild\13.20.0\buildTransitive../tools/Net70/dotnet-nswag.dll”run aspnetcoretoopenapi. json/variables:“input=\src\ApiGateway.Api\ApiGateway.Api.csproj,output=\src\ApiGateway.Api../swagger/ApiGateway. Api. json,configuration= NULL,documentName=Public API””退出,代码为-1。
ApiGateway.Api \src\Cat.Infrastructure\Build\Bull. SwaggerDocument.targets
我的控制器看起来像这样:

[ApiController]
[Route("v1/[controller]")]
public class MyController : MyControllerBase
{
    [HttpGet("{id}/result")]
    public async Task<IActionResult> Get([FromRoute] int id)
    {
        return await ForwardRequest(HttpMethod.Get, 
            "http://localhost/v2/result");
    }
}

public class MyControllerBase : ControllerBase 
{
    public async Task<IActionResult> ForwardRequest(HttpMethod httpMethod, string url, object? body = null)
    {
        // do something.
    }
}

字符串
当我把“ForwardRequest”中的逻辑放入MyController并删除继承时,一切都很好。当我开始使用MyControllerBase类时,它就中断了。
我错过了什么?

zzwlnbp8

zzwlnbp81#

你需要添加[HttpPost][HttpGet][HttpPut]等.属性到你的基类方法,但看看下面的例子

基类

public class MyControllerBase : ControllerBase
{
    public MyControllerBase()
    {
    }

    public async Task ForwardRequest([FromQuery] HttpRequest request, string url, object? body = null)
    {
       //enter code here...
    }
}

字符串

实现

[ApiController]
[Route("v1/[controller]")]
public class MyController : MyControllerBase
{
    [HttpGet("{id}/result")]
    public async Task<IActionResult> Get([FromRoute] int id)
    {
        return await ForwardRequest(HttpMethod.Get, 
            "http://localhost/v2/result");
    }
}

fjaof16o

fjaof16o2#

API端点参数中的HttpMethod可以替换为字符串。
注意:我使用[HttpPost]是因为“object?body”将是fromBody。它可以是[HttpGet],但你不能在Swagger中使用它。

using Microsoft.AspNetCore.Mvc;

namespace WebAppTestController.Controllers
{
  [ApiController]
  [Route("[controller]")]
  public class MyController : MyControllerBase
  {
    [HttpGet("{id}/result")]
    public async Task<IActionResult> Get([FromRoute] int id)
    {
      return await ForwardRequest(HttpMethod.Get.ToString(), "http://localhost/v2/result");
    }
  }

  public class MyControllerBase : ControllerBase
  {
    [HttpPost]
    public async Task<IActionResult> ForwardRequest(string method, string url, object? body = null)
    {
      var httpMethod = new HttpMethod(method);

      return Ok();
    }
  }
}

字符串

相关问题