0

This is my code in UserController and it runs well.

private Identifier GetCurrentUser()
        {
            var identity = HttpContext.User.Identity as ClaimsIdentity;
            if (identity != null)
            {
                var userClaims = identity.Claims;
                return new Identifier
                {
                    Id = userClaims.FirstOrDefault(o => o.Type == ClaimTypes.NameIdentifier)?.Value,
                    Role = userClaims.FirstOrDefault(o => o.Type == ClaimTypes.Role)?.Value,
                };
            }
            return null;
        }

enter image description here However when I change this method from private to public I got this error with swagger. enter image description here I do not understand why I get this error. Please tell me the reason and teach me how to fix it. Thank for your attention

  • 1
    can you post the full controller? – Qudus Feb 08 '22 at 08:00
  • This is my userController: https://github.com/psawn/Sem3Project/blob/main/BE/Sem3Project/Controllers/UserController.cs – Đoàn Đức Bảo Feb 08 '22 at 08:03
  • 1
    maybe you need this? - https://stackoverflow.com/questions/29701573/how-to-omit-methods-from-swagger-documentation-on-webapi-using-swashbuckle – Rand Random Feb 08 '22 at 08:05
  • 2
    public methods in a controller are automatically interpreted as endpoints and the swagger request fails, because with that extra endpoint you have conflicting routes --> multiple endpoints exist on the same route – fbede Feb 08 '22 at 08:08

2 Answers2

1

Like it has been pointed out in the comment, you have conflicting route names with api/GetUsers/{search} and api/GetUsers/{id}. It becomes difficult for the compiler to figure out which one you really want to use.

I recommend you change the GetUserById action method to this form so there's a distinction between the two routes.

[HttpGet("\GetUser\{id}")]
[Authorize(Roles = "Administrator,Staff")]
public IActionResult GetUser(string id)

Alternatively you could place the search term for GetUsers in the same class as the paginationFilter like this

public class SearchAndPagination
{
    public PaginationFilter paginationFilter {get;set;}
    public string search {get;set;}
}

Then pass as request body to GetUsers action

[HttpGet]
[Authorize(Roles = "Administrator,Staff")]
public IActionResult GetUsers([FromBody] SearchAndPagination paginationFilter)
{
    var users = _userRepository.GetUsers(paginationFilter.paginationFilter, paginationFilter.search);
    ...
}
Qudus
  • 1,440
  • 2
  • 13
  • 22
1

I had a public method in the controller, where the library I used requires only public methods, and swagger was not happy with that because could not figure out is that endpoint or not. I have to decorate the public method with NonAction annotation like below code. It solved the problem

  [NonAction]
  public void SendEmail(string text)
  { 
  }
Shaahin
  • 1,195
  • 3
  • 14
  • 22