RESTful API端点命名

时间:2019-04-02 12:06:47

标签: c# rest asp.net-core swagger

我正在研究asp.net核心2.2后端,它公开了RESTful API。

当前实现工作正常(为清晰起见,删除了其他代码):

namespace Sppd.TeamTuner.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly ITeamTunerUserService _userService;
        private readonly ITokenProvider _tokenProvider;
        private readonly IAuthorizationService _authorizationService;
        private readonly IMapper _mapper;

        public UsersController(ITeamTunerUserService userService, ITokenProvider tokenProvider, IAuthorizationService authorizationService, IMapper mapper)
        {
            _userService = userService;
            _tokenProvider = tokenProvider;
            _authorizationService = authorizationService;
            _mapper = mapper;
        }

        [HttpGet]
        public async Task<IActionResult> GetByUserId(Guid userId)
        {
            // TODO: secure this call
            var user = _userService.GetByIdAsync(userId);
            return Ok(_mapper.Map<UserDto>(await user));
        }
    }
}

单一API方法可与URL https://localhost:5001/Users?userId=4AF29C4A-282A-4FB8-8691-9D44398A97F2一起正常使用

现在我想添加第二种方法:

[HttpGet]
public async Task<IActionResult> GetByTeamId(Guid teamId)
{
    // TODO: secure this call
    var users = _userService.GetByTeamIdAsync(teamId);
    return Ok(_mapper.Map<IEnumerable<UserDto>>(await users));
}

将生成URL https://localhost:5001/Users?teamId=4AF29C4A-282A-4FB8-8691-9D44398A97F2(请注意,与首次调用相比,该参数为teamId而不是userId)。

在使用SwaggerUI进行测试时,页面不会加载,并且显示以下异常:

An unhandled exception has occurred while executing the request.
System.NotSupportedException: HTTP method "GET" & path "Users" overloaded by actions - Sppd.TeamTuner.Controllers.UsersController.GetByUserId (Sppd.TeamTuner),Sppd.TeamTuner.Controllers.UsersController.GetByTeamId (Sppd.TeamTuner). Actions require unique method/path combination for Swagger 2.0. Use ConflictingActionsResolver as a workaround
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreatePathItem(IEnumerable`1 apiDescriptions, ISchemaRegistry schemaRegistry)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreatePathItems(IEnumerable`1 apiDescriptions, ISchemaRegistry schemaRegistry)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath, String[] schemes)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

问题:
-这是SwaggerUI问题吗?意思是控制器可以正常工作吗?
-用户或团队控制器是否应公开该方法以获取所有团队用户?我们通过团队ID查询并返回用户。
-如果仍保留在“用户”控制器中,拥有唯一端点的“最佳”方法是什么?

4 个答案:

答案 0 :(得分:1)

you need to provide action name in your url.which is unique path

https://localhost:5001/Users/GetByTeamId?teamId=4AF29C4A-282A-4FB8-8691-9D44398A97F2

答案 1 :(得分:1)

您可以尝试Attribute Routing,这就是我的意思

[HttpGet("/{userId}")]
public async Task<IActionResult> GetByUserId(Guid userId)

[HttpGet("/{teamId}")]
public async Task<IActionResult> GetByTeamId(Guid teamId)

[HttpGet("/{teamId}")]用参数route定义了一个新的teamId

答案 2 :(得分:1)

我会将其放入Teams控制器中,并使用/teams/1/users之类的路由来接收它-其中1是团队ID。这是更多的“休息” :)。您需要使用[Route("{teamId}/users")].

注释您的Teams控制器操作。

但是,如果要将其保留在“用户”控制器中,请使用[Route("some-action-name/{teamId}")]注释团队操作,并使用users/some-action-name/{teamId}进行访问

答案 3 :(得分:0)

尝试在您的route属性中添加操作,不要忘记在您的url中添加操作名称

namespace Sppd.TeamTuner.Controllers
{
   [Authorize]
   [ApiController]
   [Route("[controller]/[Action]")]
 public class UsersController : ControllerBase
 {
     private readonly ITeamTunerUserService _userService;
     private readonly ITokenProvider _tokenProvider;
     private readonly IAuthorizationService _authorizationService;
     private readonly IMapper _mapper;

     public UsersController(ITeamTunerUserService userService, ITokenProvider tokenProvider, IAuthorizationService authorizationService, IMapper mapper)
    {
        _userService = userService;
        _tokenProvider = tokenProvider;
        _authorizationService = authorizationService;
        _mapper = mapper;
    }

    [HttpGet]
    public async Task<IActionResult> GetByUserId(Guid userId)
    {
        // TODO: secure this call
        var user = _userService.GetByIdAsync(userId);
        return Ok(_mapper.Map<UserDto>(await user));
    }
  }
}