[英]Get Relative Path from Route Name
當路徑被命名...
[Route("api/[controller]/{id}/Existing", Name = "ExistingOrdersLink")]
public class OrdersController : Controller {...}
...使用其名稱創建絕對路徑很容易:
var address = Url.Link("ExistingOrdersLink", new { id = 22 });
但是,我需要能夠從 Route 名稱生成相對路徑。 所以我寫了這樣的代碼:
//Is there a built-in mechanism for this?
string partial = new Uri(Url.Link("ExistingOrdersLink", new { id = id })).PathAndQuery;
以上工作,但在 ASP.NET Core 中,是否有更直接的方法來獲得相同的結果?
為什么我需要這個? 我制作的一些控制器實際上是通用的:
[Route("api/Subscribers/{id}/[controller]", "SubscriberLink")]
[Route("api/Organization/{id}/[controller]", "OrganizationLink")]
public class OrdersController<T> : Controller where T : IOrder
{
private ICommand<Order<T>> createOrder;
protected OrdersController(ICommand<Order<T>> createOrder)
{
this.createOrder = createOrder;
}
[HttpPost("{otype}")]
public async Task<IActionResult> Create(
Guid id,
[FromBody] Order<T> order)
{
order.CustomerOrderId = Guid.NewGuid();
createOrder.Handle(order);
string[] segs = Request.Path.Value.Split(new char[] { '/' },StringSplitOptions.RemoveEmptyEntries);
//This will become either "SubscriberLink" or "OrganizationLink"
string route = $"{segs[1]}Link";
//Is there a built-in mechanism for this?
string partial = new Uri(Url.Link(route, new { id = id })).PathAndQuery;
partial = $"{partial}/{order.CustomerOrderId}";
CreatedResult reply = Created(partial, null);
return reply;
}
}
我認為您正在尋找Url.RouteUrl
示例:
Url.RouteUrl("ExistingOrdersLink", new { id = 22});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.