2

When a path is named...

[Route("api/[controller]/{id}/Existing", Name = "ExistingOrdersLink")]
public class OrdersController : Controller {...}

...it is easy to create an absolute path using its name:

var address = Url.Link("ExistingOrdersLink", new { id = 22 });

However, I need the ability to generate a relative path from a Route name. So I write code like this:

//Is there a built-in mechanism for this?
string partial = new Uri(Url.Link("ExistingOrdersLink", new { id = id })).PathAndQuery;

The above works but, in ASP.NET Core, is there a more direct way to get the same result?

Context

Why do I need this? Some of the controllers I make are actually generic:

[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;
    }
}

1 Answer 1

1

I think you are looking for Url.RouteUrl Example:

Url.RouteUrl("ExistingOrdersLink", new { id = 22});
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is correct, although the XML documentation for that function is incorrect. It states "Generates a fully qualified or absolute URL...". I would not have asked this question if the documentation had been correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.