JsonApiDotNetCore自定义控制器路由无法限制及Swagger报错问题
问题解决方案
一、解决Swagger的歧义HTTP方法错误
报错提示GetSecondaryAsync方法缺少显式HTTP方法绑定,导致Swagger无法识别。解决方式如下:
在自定义控制器中重写该方法,并标记为[NonAction](如果不需要此接口),或添加对应的HTTP特性(如[HttpGet]):
[NonAction] public override Task<IActionResult> GetSecondaryAsync(CancellationToken cancellationToken) { return base.GetSecondaryAsync(cancellationToken); }
二、限制仅生成已重写方法的端点
针对JsonApiDotNetCore 5.3.0版本,有两种可靠方式实现需求:
方法1:使用[ResourceController]特性指定允许的操作
在控制器类上添加该特性,明确列出需要启用的操作类型:
[ResourceController(AllowedOperations = new[] { Operations.Get, Operations.GetById })] public class RaceController<TResource, TIdentifier> : BaseJsonApiController<TResource, TIdentifier> where TResource : class, IIdentifiable<TIdentifier> where TIdentifier : struct { // 控制器构造函数及重写方法代码 }
该方式会让JsonApiDotNetCore仅注册指定的操作端点,Swagger也只会生成对应接口。
方法2:重写不需要的基类方法并标记忽略
对于不需要的基类方法(如PostAsync、PatchAsync等),重写后添加[NonAction]特性,让Swagger忽略这些接口:
[NonAction] public override Task<IActionResult> PostAsync(TResource resource, CancellationToken cancellationToken) { return base.PostAsync(resource, cancellationToken); } [NonAction] public override Task<IActionResult> PatchAsync(TIdentifier id, JsonPatchDocument<TResource> patchDocument, CancellationToken cancellationToken) { return base.PatchAsync(id, patchDocument, cancellationToken); }
额外修正:泛型参数类型匹配问题
注意到你的GetById重写方法中参数使用了long id,但泛型参数是TIdentifier,可能导致类型不匹配,建议修改为:
[HttpGet("{id}", Name = "GetById")] public override async Task<IActionResult> GetAsync(TIdentifier id, CancellationToken cancellationToken) { var response = await base.GetAsync(id, cancellationToken); return Ok(response); }
内容的提问来源于stack exchange,提问作者Bhavik Mittal
相关产品推荐
相关产品推荐

