ASP.NET Core Web API

Cenk 1,021 Reputation points
2023-01-08T19:17:41.627+00:00

Hi,

I wonder if I can hide an action method in order not to be seen in the swagger?

Thank you.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,729 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,831 Reputation points Microsoft Vendor
    2023-01-09T02:42:05.353+00:00

    Hi @Cenk ,

    I wonder if I can hide an action method in order not to be seen in the swagger?

    You can try to use the following methods:

    Method 1: Add an ApiExplorerSettings attribute on a controller or action method, code like this:

    [Route("api/[controller]")]  
    [ApiController]  
    //[ApiExplorerSettings(IgnoreApi = true)]  
    public class ValuesController : ControllerBase  
    {  
        // GET: api/<ValuesController>  
        [ApiExplorerSettings(IgnoreApi = true)]  
        [HttpGet]  
        public IEnumerable<string> Get()  
        {  
            return new string[] { "value1", "value2" };  
        }  
    

    The result as below: the Get method was removed from the Swagger UI, but we still can access the Get method.

    277209-image.png

    Method 2: Add a custom Convention and set the IsVisible attribute to false. Code like this:

    public class ActionHidingConvention : IActionModelConvention  
    {  
        public void Apply(ActionModel action)  
        {  
            // Replace with any logic you want  
            if (action.Controller.ControllerName.ToLower() == "values")  
            {  
                action.ApiExplorer.IsVisible = false;  
            }  
        }  
    }   
    

    Then, apply convention on the service:

    builder.Services.AddControllers(o =>  
    {  
        o.Conventions.Add(new ActionHidingConvention());  
    });  
    

    The result as below:
    277268-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.