Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define links for OAS3 using Swashbuckle?

I have noticed that in the Swagger UI v3 and in OAS3 we now have support for something called "links"

But I cant really figure out if its possible to use this feature with Swashbuckle, and if it is.. then how? Been searching the net and haven't found anything regarding this..

Anyone been able to use links with Swashbuckle?

like image 969
Inx51 Avatar asked Nov 15 '22 08:11

Inx51


1 Answers

You can use an OperationFilter. Create a class that implements IOperationFilter

public class MyLinkFilter : IOperationFilter 
{

into it select the response for which you want to add Links.

public void Apply(OpenApiOperation operation, OperationFilterContext context)
    var responses = operation.Responses;
    var response = responses.FirstOrDefault(r => r.Key == "200").Value;

then update the Links property

response.Links = new Dictionary<string, OpenApiLink>
{
    { 
        "YourKey"
        ,new OpenApiLink {
            OperationId = "YourOperationId",
            Description = ".............",
            Parameters = new Dictionary<string, RuntimeExpressionAnyWrapper>
            {
                {
                    "yourParam", new RuntimeExpressionAnyWrapper
                    {
                        Any = new OpenApiString("$request.path.number")
                    }
                }
            }
        }
    }
};

Register your OperationFilter into startup.cs

services.AddSwaggerGen(options =>
  {
     options.OperationFilter<MyLinkFilter>();
  });

OpenAPI, Response

OpenAPI, Link

Finally, you'll have to implement a mechanism to apply the links to the good Action in your controller.

like image 153
Denoche88 Avatar answered Nov 24 '22 00:11

Denoche88