How to get application base url while behind reverse proxy
Asked Answered
B

1

6

Is there any way for an ASP.NET application to be able to derive its url paths and hostname knowing its own routes within the context of a request going through reverse proxy/gateway?

When requesting this url via a gateway:

http://conoso.com/behind/some/reverseproxy/api/values/

The request is being re-routed by the gateway to some other location:

http://10.0.0.0/api/values

It is accessing the following ApiController ValuesController's Get method using the DefaultApi route:

// GET api/values
public HttpResponseMessage Get()
{
  var res = Request.CreateResponse();
  res.Headers.Add(
    "Location",
    Url.Link(
      "DefaultApi",
      new
        {
          id = 1
        }));
  return res;
}

It returns the following header value:

Location: http://10.0.0.0/api/values/1

while I was hoping to be sending the valid path of:

Location: http://conoso.com/behind/some/reverseproxy/api/values/1

The alternative to using the built in methods in the framework is to manually format the string:

var baseUrl = "http://conoso.com/behind/some/reverseproxy";
string.Format("{0}/values/1", baseUrl);

But that gives off some wicked code smell. Is there a cleaner approach anyone can suggest?

Buoyage answered 9/12, 2013 at 20:5 Comment(3)
I assume you get similar results using Url.Content("~") instead of Url.Link?Nailbiting
@C.Barlow it's different but in MVC controllers, but that only returns the relative path within the application, i.e. /api/values/1 (using example from above). Using a reverse proxy gateway, this would resolve too far up the url path to be routed properly.Buoyage
There's some creative ideas here... some of them are a bit hacky but might give you what you need: #1288546Nailbiting
L
1

We exactly had the same problem behind our secure entry server. For REST calls, we wanted to generate urls on the server side to make them available in java script. But they didn't include the sub-path added by the secure entry server.

So we came up with a workaround like that (rendered in layout page):

<a id="urlBase" href="/" style="display: none;"></a>
<script type="text/javascript">
    baseUrl = document.getElementById('urlBase').getAttribute('href');
</script>

href="/" has been substitued by the entry server by href="/path/", and we could easily concatenate baseUrl with our relative paths when accessing REST services.

Hope it helps in your case too.

(i posted the same answer here, hope its ok to copy & paste)

Lovesome answered 4/3, 2014 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.