The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Global.asax.cs 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Optimization;
  7. using System.Web.Routing;
  8. using Teknik.Models;
  9. using System.Data.Entity;
  10. using System.Web.Security;
  11. using Teknik.Areas.Users.Models;
  12. using Teknik.Areas.Error.Controllers;
  13. using System.Web.Helpers;
  14. using System.Diagnostics;
  15. using Teknik.Utilities;
  16. using System.Text;
  17. using Teknik.Areas.Users.Utility;
  18. using Teknik.Security;
  19. namespace Teknik
  20. {
  21. public class MvcApplication : System.Web.HttpApplication
  22. {
  23. protected void Application_Start()
  24. {
  25. ViewEngines.Engines.Clear();
  26. ViewEngines.Engines.Add(new CustomRazorViewEngine());
  27. Database.SetInitializer(new MigrateDatabaseToLatestVersion<TeknikEntities, Migrations.Configuration>());
  28. AreaRegistration.RegisterAllAreas();
  29. AntiForgeryConfig.RequireSsl = true;
  30. MvcHandler.DisableMvcResponseHeader = true;
  31. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  32. RouteConfig.RegisterRoutes(RouteTable.Routes);
  33. BundleConfig.RegisterBundles(BundleTable.Bundles);
  34. }
  35. protected void Application_BeginRequest(object sender, EventArgs e)
  36. {
  37. // Start the generation time stopwatcher
  38. var stopwatch = new Stopwatch();
  39. HttpContext.Current.Items[Constants.PERF_KEY] = stopwatch;
  40. stopwatch.Start();
  41. // Generate the NONCE used for this request
  42. string nonce = Convert.ToBase64String(Encoding.UTF8.GetBytes(StringHelper.RandomString(24)));
  43. HttpContext.Current.Items[Constants.NONCE_KEY] = nonce;
  44. }
  45. protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
  46. {
  47. if (HttpContext.Current != null)
  48. {
  49. HttpContext context = HttpContext.Current;
  50. // Don't server HSTS over HTTP
  51. if (context.Request.Url.Scheme != "https")
  52. HttpContext.Current.Response.Headers.Remove("strict-transport-security");
  53. // Remove stupid headers
  54. context.Response.Headers.Remove("Server");
  55. }
  56. }
  57. protected void Application_EndRequest(object sender, EventArgs e)
  58. {
  59. try
  60. {
  61. HttpContext context = HttpContext.Current;
  62. // Set the generation time in the header
  63. Stopwatch stopwatch = (Stopwatch)context.Items[Constants.PERF_KEY];
  64. stopwatch.Stop();
  65. TimeSpan ts = stopwatch.Elapsed;
  66. string elapsedTime = String.Format("{0} seconds", ts.TotalSeconds);
  67. context.Response.AppendHeader("GenerationTime", elapsedTime);
  68. }
  69. catch (Exception ex)
  70. {
  71. if (!ex.Message.Contains("Server cannot append header after HTTP headers have been sent"))
  72. {
  73. // Just log it
  74. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Application_EndRequest", ex);
  75. }
  76. }
  77. }
  78. protected void Application_Error(object sender, EventArgs e)
  79. {
  80. Exception exception = null;
  81. try
  82. {
  83. // Get the last exception
  84. exception = Server.GetLastError();
  85. // Clear the response
  86. Response.Clear();
  87. HttpException httpException = exception as HttpException;
  88. RouteData routeData = new RouteData();
  89. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  90. routeData.DataTokens.Add("area", "Error");
  91. routeData.Values.Add("controller", "Error");
  92. routeData.Values.Add("scheme", "https");
  93. if (httpException == null)
  94. {
  95. routeData.Values.Add("action", "Exception");
  96. }
  97. else //It's an Http Exception, Let's handle it.
  98. {
  99. switch (httpException.GetHttpCode())
  100. {
  101. case 401:
  102. // Unauthorized.
  103. routeData.Values.Add("action", "Http401");
  104. break;
  105. case 403:
  106. // Forbidden.
  107. routeData.Values.Add("action", "Http403");
  108. break;
  109. case 404:
  110. // Page not found.
  111. routeData.Values.Add("action", "Http404");
  112. break;
  113. case 500:
  114. // Server error.
  115. routeData.Values.Add("action", "Http500");
  116. break;
  117. // Here you can handle Views to other error codes.
  118. // I choose a General error template
  119. default:
  120. routeData.Values.Add("action", "General");
  121. break;
  122. }
  123. }
  124. // Pass exception details to the target error View.
  125. routeData.Values.Add("exception", exception);
  126. // Clear the error on server.
  127. Server.ClearError();
  128. // Avoid IIS7 getting in the middle
  129. Response.TrySkipIisCustomErrors = true;
  130. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  131. if (new HttpRequestWrapper(Request).IsAjaxRequest())
  132. {
  133. string jsonResult = string.Empty;
  134. if (httpException == null)
  135. {
  136. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.GetFullMessage(true) } });
  137. }
  138. else
  139. {
  140. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.GetFullMessage(true) } });
  141. }
  142. Response.Write(jsonResult);
  143. }
  144. else
  145. {
  146. // Call target Controller and pass the routeData.
  147. IController errorController = new ErrorController();
  148. errorController.Execute(new RequestContext(
  149. new HttpContextWrapper(Context), routeData));
  150. }
  151. }
  152. catch (Exception ex)
  153. {
  154. // Unable to display error, so try to log it
  155. try
  156. {
  157. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Application_Error", ex);
  158. if (exception != null)
  159. {
  160. Logging.Logger.WriteEntry(Logging.LogLevel.Error, "Exception Thrown", exception);
  161. }
  162. }
  163. catch(Exception) { }
  164. }
  165. }
  166. }
  167. }