code_junkie

Best way in asp.net to force https for an entire site?

Nov 10th, 2011
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. protected void Application_BeginRequest(Object sender, EventArgs e)
  2. {
  3. if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
  4. {
  5. Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
  6. + HttpContext.Current.Request.RawUrl);
  7. }
  8. }
  9.  
  10. using System;
  11. using System.Web;
  12.  
  13. namespace HttpsOnly
  14. {
  15. /// <summary>
  16. /// Redirects the Request to HTTPS if it comes in on an insecure channel.
  17. /// </summary>
  18. public class HttpsOnlyModule : IHttpModule
  19. {
  20. public void Init(HttpApplication app)
  21. {
  22. // Note we cannot trust IsSecureConnection when
  23. // in a webfarm, because usually only the load balancer
  24. // will come in on a secure port the request will be then
  25. // internally redirected to local machine on a specified port.
  26.  
  27. // Move this to a config file, if your behind a farm,
  28. // set this to the local port used internally.
  29. int specialPort = 443;
  30.  
  31. if (!app.Context.Request.IsSecureConnection
  32. || app.Context.Request.Url.Port != specialPort)
  33. {
  34. app.Context.Response.Redirect("https://"
  35. + app.Context.Request.ServerVariables["HTTP_HOST"]
  36. + app.Context.Request.RawUrl);
  37. }
  38. }
  39.  
  40. public void Dispose()
  41. {
  42. // Needed for IHttpModule
  43. }
  44. }
  45. }
  46.  
  47. <httpModules>
  48. <add name="HttpsOnlyModule" type="HttpsOnly.HttpsOnlyModule, HttpsOnly" />
  49. </httpModules>
  50.  
  51. <rewrite>
  52. <rules>
  53. <rule name="Redirect HTTP to HTTPS" stopProcessing="true">
  54. <match url="(.*)"/>
  55. <conditions>
  56. <add input="{HTTPS}" pattern="^OFF$"/>
  57. </conditions>
  58. <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/>
  59. </rule>
  60. </rules>
  61. </rewrite>
Add Comment
Please, Sign In to add comment