Asp.Net核心Swashbuckle设置operationId [英] Asp.Net core Swashbuckle set operationId
本文介绍了Asp.Net核心Swashbuckle设置operationId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在Asp.Net Core 2.1项目中设置摇摇欲坠的operationId
属性?根据这篇帖子,我应该使用SwaggerOperationAttribute
,但是我在Swashbuckle.AspNetCore库中找不到它.还有一个IOperationFilter
How can I set swagger operationId
attribute in Asp.Net Core 2.1 project? According to this post I should use SwaggerOperationAttribute
but I cannot find it in Swashbuckle.AspNetCore library. Also there is an IOperationFilter
public interface IOperationFilter
{
void Apply(Operation operation, OperationFilterContext context);
}
而且我找不到为实现摇摇欲坠的目的而实现的任何实现方式.
and I can't find any implementations for swagger generation purposes.
推荐答案
最后,我来到了这个解决方案:
Finally, I came to this solution:
public class SwaggerOperationNameFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
operation.OperationId = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<SwaggerOperationAttribute>()
.Select(a => a.OperationId)
.FirstOrDefault();
}
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class SwaggerOperationAttribute : Attribute
{
public SwaggerOperationAttribute(string operationId)
{
OperationId = operationId;
}
public string OperationId { get; }
}
// Startup.cs
services.AddSwaggerGen(c =>
{
...
c.OperationFilter<SwaggerOperationNameFilter>();
};
[HttpGet("{id:int}")]
[SwaggerOperation("GetById")]
public async Task<IActionResult> Get(int id)
{
...
}
但是在我看来,我还是重新发明了轮子.
But it still seems to me that I've reinvented the wheel.
这篇关于Asp.Net核心Swashbuckle设置operationId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文