0

We have a project that uses multiple domains (with tenants) and when we need to generate an absolute url we used to do this:

var forgotUrl = Url.Action("Forgot", "Account", null, this.Request.Url.Scheme);

That worked well, and sometimes you need absolute urls when for instance sending out emails with reset password links.


However, we have now implemented SSL with reverse proxy, meaning that this.Request.Url.Scheme no longer gives us the correct domain.

Therefore we have to do something like this instead

var forgotUrl = CurrentHostWithSchemeWithoutTrailingSlash + Url.Action("Forgot", "Account");

To simplify we have made an extension method, like so

Url.AbsoluteAction("Forgot", "Account", *data*)

And that all works like expected, so everything is well, however, you can still mess upp by writing a line calling the original Url.Action and sending in this.Request.Url.Scheme.

So my question is simply: Is there any way of blocking usage of that, either hiding it, or giving compiler errors, warnings, anything?

Rickard Liljeberg
  • 966
  • 1
  • 12
  • 39
  • Possible duplicate of [Finding all references to a method with Roslyn](http://stackoverflow.com/questions/31861762/finding-all-references-to-a-method-with-roslyn) – Keith Hall Feb 03 '17 at 13:27
  • Can you use Resharper? – Evk Feb 03 '17 at 13:34
  • So, you could use a derived `Controller` class as the base for all your controllers and overwrite the `Url` property. For views, this looks relevant: [Changing Base Type Of A Razor View](http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx/) – spender Feb 03 '17 at 13:35
  • @KeithHall I think it is good link, but I don't think it covers this question completely - so not really duplicate. (I've edited link into an answer) – Alexei Levenkov Feb 05 '17 at 06:43

1 Answers1

1

For general case where the method is class member your real option is to find usages and update code. You can either manually find all the cases of such functions with "find all usages" (VS or VS+R#) from time to time or use automated tools. If you use VS 2015+ see Finding all references to a method with Roslyn. For older versions or build tests you can scan code e.g. by adding unit test that will load assembly, parse IL and assert wrong methods.

For this particular case Since Url.Action is extension method - additional option is to create another extension method with the same signature in another static class that is visible by default in the view (e.g. namespace System; public static class MyHack{ ...Action(UrlHelper...) so compiler will find 2 variants of the method and show an error.

Also educating developers (i.e. during code reviews) and available existing code is often enough. If there is already existing example in the project that does this correctly there is good chance that it will be simply copy-pasted.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179