Set Location URI point to another controller

Viewed 102

I have a controller with an action and I want to set the LocationUri to point to another controller. For example, I have:

[Route("auth")]
[ApiController]
public class AuthorisationController
{
        [Route("{id}")]
        public IActionResult Put([FromRoute]string id, [FromBody]FooBar request)
        {
            return new CreatedResult("locationUri", SanitiseResponse(request));
        }
}

I want the LocationUri to point to this controller

[Route("transaction")]
[ApiController]
public class TransactionController
{
    [Route("{id}")]
    public IActionResult Get([FromRoute] string id)
    {
        return new OkResult();
    }
}

Any ideas how I do this? I was constructing it myself using _httpContextAccessor but wondered if there was a better way?

1 Answers

This is where deriving from ControllerBase can help since it provides a helper member that simplifies what you are trying to achieve

[Route("auth")]
[ApiController]
public class AuthorisationController : ControllerBase {
    [Route("{id}")]
    public IActionResult Put([FromRoute]string id, [FromBody]FooBar request) {
        return CreatedAtAction("Get", "Transaction", { id = ??? }, SanitiseResponse(request));
    }
}

Reference ControllerBase.CreatedAtAction Method

You still can do it yourself using the CreatedAtActionResult

[Route("auth")]
[ApiController]
public class AuthorisationController {
    [Route("{id}")]
    public IActionResult Put([FromRoute]string id, [FromBody]FooBar request) {
        return new CreatedAtActionResult("Get", "Transaction", { id = ??? }, SanitiseResponse(request));
    }
}

which is basically what the helper method wraps.

Note the ??? in the exmaples where you would specify the id routeValue which in this case is part of the generated URI

To avoid hard-coding the action and controller you can do the following, but I find it rather verbose.

//...

string actionName = nameof(TransactionController.Get);
string controllerName = nameof(TransactionController).TrimEnd("Controller");

return CreatedAtAction(actionName, controllerName, { id = ??? }, SanitiseResponse(request));

//...

If the controller name or action name is refactored, this would allow for the IDE to make the changes automatically or show a syntax error, alerting you to the change.

Related