Lup*_*upa 5 c# rest swagger-ui asp.net-core
将 ASP.Net Core 3.1 与 NuGet 中的 NSwag.AspNetCore v13.7.0 结合使用
我有这个动作方法
[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
}
}
Run Code Online (Sandbox Code Playgroud)
GetPersonInput 是:
public class GetPersonInput
{
[FromQuery]
public IdentityType? IdentityType { get; set; }
[FromRoute]
public string IdentityNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当我从邮递员调用它时,它工作正常。但是当我从 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"
Run Code Online (Sandbox Code Playgroud)
产生这个请求:
https://localhost:44343/api/person/{identityNumber}?identityType=DU
Run Code Online (Sandbox Code Playgroud)
这会导致异常:
System.FormatException: Input string was not in a correct format.
Run Code Online (Sandbox Code Playgroud)
这是我的启动配置
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();
});
}
Run Code Online (Sandbox Code Playgroud)
其实很简单,路由参数区分大小写。只需更改{identityNumber}为{IdentityNumber}:
[HttpGet("{IdentityNumber}", Name = nameof(GetPersonById))]
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Get))]
public ActionResult<PersonResource> GetPersonById([FromQuery] GetPersonInput input)
{
//code omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2045 次 |
| 最近记录: |