Best way to hide a parameter in Swagger

Viewed 1804

I'm building an API where I have a couple of endpoints where I need the User ID, so after getting the idea from the most voted answer (not the accepted one) from this post: ASP.NET MVC Pass object from Custom Action Filter to Action.

I created an Action Filter that I can set up just with the [UserIdFromToken] attribute.

So I'm basically getting the User ID through this Action Filter that gets it from the authorization header this way:

[Authorize]
[UserIdFromToken]
public IActionResult Get(Guid userId /* Got from the [UserIdFromToken] filter */)
{
   return Ok(_userService.Get(userId));
}

The only problem is now it's showing the parameter userId as a Required parameter (and I don't want to show it at all) in my Swagger documentation, which is obviously false, since I don't need any input beyond the authorization header.

Is there any way to get my swagger documentation cleaner, without showing this parameter?

Do you think it would be better to try another approach to get the userId such as the accepted option from the post I sent above?

1 Answers

I realize this is an old post, but if anyone have similar issues you can create your own action filter by extending Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter like this:

public class HideUserIdOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var scopes = context.MethodInfo
            .GetCustomAttributes(true)
            .OfType<UserIdFromTokenAttribute>()
            .Distinct();

        if (scopes.Any())
        {
            operation.Parameters = operation.Parameters.Where(param => param.Name != "userId").ToList();
        }
    }
}

Remember to add the operation filter to your swagger gen:

c.OperationFilter<HideUserIdOperationFilter>();
Related