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 6.6KB

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