Get original url without non-standard port (C#)

Daryl Teo picture Daryl Teo · Oct 6, 2011 · Viewed 10.4k times · Source

First question!


Environment

MVC, C#, AppHarbor.

Problem

I am calling an openid provider, and generating an absolute callback url based on the domain.

On my local machine, this works fine if I hit http://localhost:12345/login

Request.Url; //gives me `http://localhost:12345/callback`

However, on AppHarbor where I'm deploying, because they are using non-standard ports, even if I'm hitting it at "http://sub.example.com/login"

Request.Url; //gives me http://sub.example.com:15232/callback

And this screws up my callback, because the port number wasn't in the original source url!

I've tried

  • Request.Url
  • Request.Url.OriginalString
  • Request.RawUrl

All gives me "http://sub.example.com:15232/callback".

Also to clear up that this isn't a Realm issue, the error message I am getting from DotNetOpenAuth is

'http://sub.example.com:14107/accounts/openidcallback' not under realm 'http://*.example.com/'. 

I don't think I've stuffed that up?

Now, I'm about to consider some hacky stuff like

  • preprocessor commands (#IF DEBUG THEN PUT PORT)
  • string replace (Request.URL.Contains("localhost"))

All of these are not 100% solutions, but I'm sick of mulling over what could be a simple property that I am missing. I have also read this but that doesn't seem to have an accepted answer (and is more about the path rather than the authority). So I'm putting it towards you guys.

Summary

So if I had http://localhost:12345/login, I need to get http://localhost:12345/callback from the Request context.

And if I had "http://sub.example.com/login", I should get "http://sub.example.com/callback", regardless of what port it is on.

Thanks! (Sleep time, will answer any questions in the morning)

Answer

runesoerensen picture runesoerensen · Oct 9, 2011

This is a common problem in load balanced setups like AppHarbor's - we've provided an example workaround.

Update: A more desirable solution for many ASP.NET applications may be to set the aspnet:UseHostHeaderForRequestUrl appSetting to true. We (AppHarbor) have seen several customers experience issues using it with their WCF apps, which is why we haven't enabled it by default and stil recommend the above solution for those situations. You can configure it using AppHarbor's "Configuration Variables" to inject the appsettings when deployed. More information can be found in this article.