我需要使一个ASP.NET Core, Web API
,支持多个HttpGet
动词与唯一的区别是查询字符串,但似乎查询字符串不能是路由模板的一部分-是真的吗?
路由模板非常相似,实际上它们只是在查询字符串上有所不同。
[Authorize]
public class SymbolsController : Controller
{
[
HttpGet,
Route("api/symbols")
]
public Task<IEnumerable<Symbol>> Symbols([FromServices] ISymbolService symbolService)
{
return symbolService.GetSymbolsAsync();
}
[
HttpGet,
Route("api/symbols?{childrenOf=id}")
]
public Task<IEnumerable<Symbol>> ValidChildren(
[FromQuery] Guid id,
[FromServices] ISymbolService symbolService)
{
return symbolService.GetValidChildrenAsync(id);
}
}
这会抛出一个异常,因为?
在路由模板中不是一个有效的字符。我怎样才能做到这一点呢?
我想出了一个更简单、更直接的解决方案。我只是使用FromQuery
属性并使模板简单。我检查id
变量是否存在,并相应地处理它。
[HttpGet, Route("api/symbols")]
public Task<IEnumerable<Symbol>> Symbols(
[FromQuery] Guid id,
[FromServices] ISymbolService symbolService) =>
id == default
? symbolService.GetSymbolsAsync()
: symbolService.GetValidChildrenAsync(id);
//eg GET api/symbols
//eg GET api/symbols?childrenOf={someGuid}
[HttpGet("api/symbols")]
public Task<IEnumerable<Symbol>> Symbols(
[FromServices] ISymbolService symbolService,
Guid? childrenOf = null)
{
if (childredOf.HasValue) {
return ValidChildren(childredOf.Value, symbolService);
}
return symbolService.GetSymbolsAsync();
}
Task<IEnumerable<Symbol>> ValidChildren(
Guid id,
ISymbolService symbolService)
{
return symbolService.GetValidChildrenAsync(id);
}