I am using attribute routing and this is how I mapped one of my create actions:
[Route("Create/{companyId:guid?}/{branchId:guid?}/{departmentId:guid?}")]
[Route("Create/{companyId:guid?}/{departmentId:guid?}")]
public async Task<ActionResult> Create(Guid? companyId, Guid? branchId, Guid? departmentId)
I also tried with two different actions that map to the same action name, like this:
[Route("Create/{companyId:guid?}/{branchId:guid?}/{departmentId:guid?}")]
public async Task<ActionResult> Create(Guid? companyId, Guid? branchId, Guid? departmentId)
[Route("Create/{companyId:guid?}/{departmentId:guid?}")]
[ActionName("Create")]
public async Task<ActionResult> CreateWithDepartmentOnly(Guid? companyId, Guid? departmentId)
It's set up like this because there might not be a branchId
and you can't have an empty parameter.
Works OK when only the companyId
is provided, or when both the companyId
and the departmentId
are provided.
When the branchId
is provided, that ID is added as query string, not as a routing parameter. This happens when I had two different actions and also doesn't matter whether the departmentId
is provided.
My code works in all scenarios, I just want to clean up the URL and not have any query strings there. Any solution or workarounds?
EDIT 1
I tried both of Slicksim's ideas.
- Setting the order of the routes had no effect
- Naming the routes did the trick, but only if all 3 IDs are provided, leaving out the
departmentId
which is the last parameter should have no effect, but instead thebranchId
got ignored
EDIT 2
The logic goes like this:
- A Company can have branches and/or departments
- A Branch can have departments
- A Department can have departments
- A Department doesn't have to have a branch
Depending on where you're creating the the department from, those IDs are in the route. Is this a viable solution?
[Route("Create/{companyId:guid}")]
[Route("Create/{companyId:guid}/{branchId:guid?}")]
[Route("Create/{companyId:guid}/{departmentId:guid?}")]
[Route("Create/{companyId:guid}/{branchId:guid?}/{departmentId:guid?}")]
public async Task<ActionResult> Create(Guid companyId, Guid? branchId, Guid? departmentId)
Are the routes 2 and 3 going to work since they both have same number and type of parameters. If the Id is placed in the correctly named parameters in the action then I'm golden.