【发布时间】:2020-04-26 20:17:34
【问题描述】:
阿罗哈 :D 我想创建一个动态路由绑定。 我的意思是,基本上是用动态路由替换查询字符串。
示例: 而不是这个:
POST http://localhost:5000/api/documents?templatename=individualemploymentagreement
这个:
POST http://localhost:5000/api/documents/individualemploymentagreement
注意: 在“http://localhost:5000/api/documents/”之后我想放任何我想要的东西,但是这条路线总是会被使用,之后的东西应该像变量一样使用。显然,这将导致目前不存在的 API Route。但是有什么办法可以解决吗?
注意 2: 我想使用它的原因是: - 根据 RESTful 服务“规则”,查询字符串应该只用于查询,在这种情况下,我没有使用查询,我调用的是通用文档服务,但是,它在需要时处理每个文档略有不同。所以在我的情况下不建议使用查询字符串。 - 该服务将处理数百种文档类型,因此我无法真正为每种类型创建不同的路径/api。所以也不推荐这样做。
我的代码(我在其中使用 {templateName} 的查询字符串:
namespace DocumentGenerator.Api.Controllers
{
[Route("api/{controller}")]
[ApiController]
public class DocumentsController : ControllerBase
{
//useless details
[HttpPost]
public async Task<IActionResult> Generate([FromQuery] string templateName, [FromBody] object properties)
{
// according to {templateName} do this or that...
// useless details
}
}
}
我想要的代码:
namespace DocumentGenerator.Api.Controllers
{
[Route("api/{controller}")]
[ApiController]
public class DocumentsController : ControllerBase
{
//useless details
[HttpPost("{templateName}"]
public async Task<IActionResult> Generate([FromBody] object properties)
{
// according to {templateName} do this or that...
// useless details
}
}
}
【问题讨论】:
-
dynamic route binding不是这个意思。路由已经是动态的,你要问的是路由是如何工作的。在默认路由模板{controller=Home}/{action=Index}/{id?}中,路由中的“{id}”部分已经 包含第二个斜杠之后的所有内容。如果您调用操作参数id而不是templateName,您将能够直接获取它。您要问的是重写 URL 或硬编码 一些参数-例如使用Generate作为操作和{templateName}作为参数而不是@987654333 @ -
你试过
[HttpPost("{templateName}"] public async Task<IActionResult> Generate(string templateName, [FromBody] object properties)或[HttpPost("/documents/{"templateName}"] .....吗? -
Panagiotis Kanavos,你是对的。这就是它的基本工作方式。当然,我以前像这样“{controller=Home}/{action=Index}/{id?}”使用它。我只是没有建立联系。谢谢。
-
一开始我也没有 - 我发布了第一条评论,然后我记得我以前看过这个只是为了找到an exact example in the docs。看起来你甚至可以使用
[Route("/dog{token}cat")])!
标签: c# rest asp.net-core asp.net-web-api