ASP.NET 核心、Web API 以查询字符串为模板的 RouteAttribute
ASP.NET Core, Web API RouteAttribute with query string as template
我需要制作一个 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);
}
}
这会引发异常,因为 ?
不是路由模板中的有效字符。我怎样才能做到这一点?
//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);
}
我想出了一个更简单、更直接的解决方案。我只是使用 FromQuery
属性并使模板保持简单。我检查 id
变量是否存在并相应地处理它。
[HttpGet, Route("api/symbols")]
public Task<IEnumerable<Symbol>> Symbols(
[FromQuery] Guid id,
[FromServices] ISymbolService symbolService) =>
id == default
? symbolService.GetSymbolsAsync()
: symbolService.GetValidChildrenAsync(id);
我需要制作一个 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);
}
}
这会引发异常,因为 ?
不是路由模板中的有效字符。我怎样才能做到这一点?
//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);
}
我想出了一个更简单、更直接的解决方案。我只是使用 FromQuery
属性并使模板保持简单。我检查 id
变量是否存在并相应地处理它。
[HttpGet, Route("api/symbols")]
public Task<IEnumerable<Symbol>> Symbols(
[FromQuery] Guid id,
[FromServices] ISymbolService symbolService) =>
id == default
? symbolService.GetSymbolsAsync()
: symbolService.GetValidChildrenAsync(id);