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.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. // Don't server HSTS over HTTP
  48. if (HttpContext.Current.Request.Url.Scheme != "https")
  49. HttpContext.Current.Response.Headers.Remove("strict-transport-security");
  50. // Remove stupid headers
  51. HttpContext.Current.Response.Headers.Remove("Server");
  52. }
  53. protected void Application_EndRequest(object sender, EventArgs e)
  54. {
  55. try
  56. {
  57. HttpContext context = HttpContext.Current;
  58. // Set the generation time in the header
  59. Stopwatch stopwatch = (Stopwatch)context.Items[Constants.PERF_KEY];
  60. stopwatch.Stop();
  61. TimeSpan ts = stopwatch.Elapsed;
  62. string elapsedTime = String.Format("{0} seconds", ts.TotalSeconds);
  63. context.Response.AppendHeader("GenerationTime", elapsedTime);
  64. }
  65. catch (Exception ex)
  66. {
  67. if (!ex.Message.Contains("Server cannot append header after HTTP headers have been sent"))
  68. {
  69. // Just log it
  70. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Application_EndRequest", ex);
  71. }
  72. }
  73. }
  74. protected void Application_Error(object sender, EventArgs e)
  75. {
  76. Exception exception = null;
  77. try
  78. {
  79. // Get the last exception
  80. exception = Server.GetLastError();
  81. // Clear the response
  82. Response.Clear();
  83. HttpException httpException = exception as HttpException;
  84. RouteData routeData = new RouteData();
  85. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  86. routeData.DataTokens.Add("area", "Error");
  87. routeData.Values.Add("controller", "Error");
  88. routeData.Values.Add("scheme", "https");
  89. if (httpException == null)
  90. {
  91. routeData.Values.Add("action", "Exception");
  92. }
  93. else //It's an Http Exception, Let's handle it.
  94. {
  95. switch (httpException.GetHttpCode())
  96. {
  97. case 401:
  98. // Unauthorized.
  99. routeData.Values.Add("action", "Http401");
  100. break;
  101. case 403:
  102. // Forbidden.
  103. routeData.Values.Add("action", "Http403");
  104. break;
  105. case 404:
  106. // Page not found.
  107. routeData.Values.Add("action", "Http404");
  108. break;
  109. case 500:
  110. // Server error.
  111. routeData.Values.Add("action", "Http500");
  112. break;
  113. // Here you can handle Views to other error codes.
  114. // I choose a General error template
  115. default:
  116. routeData.Values.Add("action", "General");
  117. break;
  118. }
  119. }
  120. // Pass exception details to the target error View.
  121. routeData.Values.Add("exception", exception);
  122. // Clear the error on server.
  123. Server.ClearError();
  124. // Avoid IIS7 getting in the middle
  125. Response.TrySkipIisCustomErrors = true;
  126. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  127. if (new HttpRequestWrapper(Request).IsAjaxRequest())
  128. {
  129. string jsonResult = string.Empty;
  130. if (httpException == null)
  131. {
  132. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.GetFullMessage(true) } });
  133. }
  134. else
  135. {
  136. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.GetFullMessage(true) } });
  137. }
  138. Response.Write(jsonResult);
  139. }
  140. else
  141. {
  142. // Call target Controller and pass the routeData.
  143. IController errorController = new ErrorController();
  144. errorController.Execute(new RequestContext(
  145. new HttpContextWrapper(Context), routeData));
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. // Unable to display error, so try to log it
  151. try
  152. {
  153. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Application_Error", ex);
  154. if (exception != null)
  155. {
  156. Logging.Logger.WriteEntry(Logging.LogLevel.Error, "Exception Thrown", exception);
  157. }
  158. }
  159. catch(Exception) { }
  160. }
  161. }
  162. }
  163. }