[英]How To get Id from the url Path
My question may look simple but I'm stuck in this problem for a while.我的问题可能看起来很简单,但我在这个问题上停留了一段时间。
Code Controller:代码 Controller:
[Route("api/ReceiptOrders/{receiptOrderNo}/[controller]")]
[ApiController]
public class ReceiptPositionsController : ControllerBase
{
[HttpPost("{orderNo}")]
public async Task<IActionResult> PostReceiptOrderPositions(
[FromBody] IEnumerable<ReceiptPositionForCreationDto> receiptPositions)
{
var receiptOrder = await _repositoryManager.ReceiptOrder.GetReceiptOrderByOrderNoAsync(receiptOrderNo, false);
//More code here...
}
}
URL: https://localhost:7164/api/ReceiptOrders/RO-20220731-4/ReceiptPositions
URL: https://localhost:7164/api/ReceiptOrders/RO-20220731-4/ReceiptPositions
my question is: how to get the ReceiptOrderNo(RO-20220731-4 in this case)?我的问题是:如何获得 ReceiptOrderNo(在这种情况下为 RO-20220731-4)? I need it to fill "GetReceiptOrderByOrderNoAsync" method.我需要它来填充“GetReceiptOrderByOrderNoAsync”方法。
Bind to the template entry by adding another parameter in your method.通过在您的方法中添加另一个参数来绑定到模板条目。 In addition, remove the template from the method's attribute.此外,从方法的属性中删除模板。 A method's template is appended to the class's template, so what you currently have won't match.方法的模板附加到类的模板中,因此您当前拥有的内容将不匹配。
[Route("api/ReceiptOrders/{receiptOrderNo}/[controller]")]
[ApiController]
public class ReceiptPositionsController : ControllerBase
{
[HttpPost] // <--- no template
public async Task<IActionResult> PostReceiptOrderPositions(
[FromRoute] string receiptOrderNo, // <---- new parameter
[FromBody] IEnumerable<ReceiptPositionForCreationDto> receiptPositions)
{
// ... use "receiptOrderNo"
}
You don't need [FromRoute]
, but I think it's a good idea as it makes it explicit where the value should be read from, instead of accidently read from a Query String or another source.您不需要[FromRoute]
,但我认为这是一个好主意,因为它明确了应该从哪里读取值,而不是从查询字符串或其他来源意外读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.