gpt4 book ai didi

c# - Swagger UI 尝试操作方法不替换路由参数,而是发送占位符 "{paramName}"

转载 作者:行者123 更新时间:2023-12-02 02:39:26 26 4
gpt4 key购买 nike

将 ASP.Net Core 3.1 与来自 NuGet 的 NSwag.AspNetCore v13.7.0 结合使用

我有这个 Action 方法

[ApiController]
[ApiVersion(EosApiVersion.CurrentVersion)]
[Route(EosApiConsts.BaseRoute + "/[Controller]")]
public class PartyController : ControllerBase
{

[HttpGet("{identityNumber}", Name = nameof(GetPersonById))]
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Get))]
public ActionResult<PersonResource> GetPersonById([FromQuery] GetPersonInput input)
{
//code omitted for brevity
}

}

GetPersonInput 是:

public class GetPersonInput
{
[FromQuery]
public IdentityType? IdentityType { get; set; }

[FromRoute]
public string IdentityNumber { get; set; }
}

当我从 Postman 调用它时,它工作正常。但是当我从很好地识别方法签名的 Swagger UI 调用它时,它会将 /{IdentityNumber} 传递给 URI,而不是我在 UI 中输入的数字:

实际调用是(来自 Postman):https://localhost:44343/api/person/25062140?identityType=DU

但是 swagger UI 构建了这个 curl :

curl -X GET "https://localhost:44343/api/person/{identityNumber}?identityType=DU" -H "accept: application/json"

产生这个请求:

https://localhost:44343/api/person/{identityNumber}?identityType=DU

导致异常:

System.FormatException: Input string was not in a correct format.

这是我的启动配置

public void ConfigureServices(IServiceCollection services)
{

//Add routing
services.AddRouting(options =>
{
options.LowercaseUrls = true;
});

services.AddControllers();
//services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //The problem also happens with CompatiblityVersion set to 2.2

//Add OpenApi
services.AddOpenApiDocument();

services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0, status: "dev");
options.ApiVersionReader = new QueryStringApiVersionReader();
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
});
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseHttpsRedirection();

//Use OpenApi with UIs
app.UseOpenApi();
app.UseSwaggerUi3();
//app.UseReDoc();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

最佳答案

其实很简单,路由参数区分大小写。只需将 {identity Number} 更改为 {Identity Number}:

[HttpGet("{IdentityNumber}", Name = nameof(GetPersonById))]
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Get))]
public ActionResult<PersonResource> GetPersonById([FromQuery] GetPersonInput input)
{
//code omitted for brevity
}

关于c# - Swagger UI 尝试操作方法不替换路由参数,而是发送占位符 "{paramName}",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63836073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com