✅ Is it possible to access a Controller's URI at runtime?
I'm not well versed in MVC structures, so this very well could be a XY problem. Let me know if it is a bad idea to begin with.
I'm trying to create a GET endpoint for
/collections
which returns Collections. One Collection
always contains a nested Model User
.
On its own, this is not a problem. However, I am creating my API based around application/hal+json
, which requires Resources to have a link to point to their exact location.
So when accessing a returned Collection
, I could use its related link if I wish to access it directly instead.
It looks sort of like this:
Endpoints:
/collections
/collections/{uuid}
This is all well and good, but I have some concerns with generating the embedded collection's link.
If I hardcode it as $"http://foo-api/collections/{uuid}"
, then I would have to change the domain in every location where I did it.
Is it possible to access the CollectionController#GetById(string uuid)
somehow and extract its URI at runtime?9 Replies
You can use reflection to get at the routing attribute, but that could be quite nasty
Or are you asking about how to get the domain?
Either one is of help, since the href should already be a filled out URL
At least I don't expect to change my endpoints constantly, so that is okay to be hardcoded for this size of a project
Ah ok, when I’ve done this before I just grabbed the Host header from the request (via HttpContext.Request.Host)
This is required to be set for all HTTP requests and iirc shouldnt be messed up by a reverse proxy
But I don’t know if that’s the ideal way to do it, I’ve not seen it being done elsewhere 😅
hmm, I see. I'll read up on the HttpContext then
thanks for the advice
As dreadfully said, the recommended approach is to extract it from the request.
and it should have the correct info even when using reverse proxy, assuming header forwarding is turned on
alternatively you create an
IOptions<T>
object where you store your root-domain^ that too, when I’ve deployed stuff like Grafana I’ve had to specify a domain in the config, so I assume they might be doing something like this for their redirects
:HmmNotes: sounds like a plan. These keywords should be enough to solve the post. Do I just mark it with :greencheck: ?
$solve
Idk
There’s a slash command
Close
$close
If you have no further questions, please use /close to mark the forum thread as answered