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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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_PostAuthenticateRequest(Object sender, EventArgs e)
  69. //{
  70. // // We support both Auth Tokens and Cookie Authentication
  71. // // Username and Roles for the current user
  72. // string username = string.Empty;
  73. // bool hasAuthToken = false;
  74. // if (Request != null)
  75. // {
  76. // if (Request.Headers.HasKeys())
  77. // {
  78. // string auth = Request.Headers["Authorization"];
  79. // if (!string.IsNullOrEmpty(auth))
  80. // {
  81. // string[] parts = auth.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  82. // string type = string.Empty;
  83. // string value = string.Empty;
  84. // if (parts.Length > 0)
  85. // {
  86. // type = parts[0].ToLower();
  87. // }
  88. // if (parts.Length > 1)
  89. // {
  90. // value = parts[1];
  91. // }
  92. // using (TeknikEntities entities = new TeknikEntities())
  93. // {
  94. // // Get the user information based on the auth type
  95. // switch (type)
  96. // {
  97. // case "basic":
  98. // KeyValuePair<string, string> authCreds = StringHelper.ParseBasicAuthHeader(value);
  99. // bool tokenValid = UserHelper.UserTokenCorrect(entities, authCreds.Key, authCreds.Value);
  100. // if (tokenValid)
  101. // {
  102. // // it's valid, so let's update it's Last Used date
  103. // UserHelper.UpdateTokenLastUsed(entities, authCreds.Key, authCreds.Value, DateTime.Now);
  104. // // Set the username
  105. // username = authCreds.Key;
  106. // }
  107. // break;
  108. // default:
  109. // break;
  110. // }
  111. // }
  112. // }
  113. // }
  114. // }
  115. // if (FormsAuthentication.CookiesSupported == true && !hasAuthToken)
  116. // {
  117. // if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
  118. // {
  119. // //let us take out the username now
  120. // username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
  121. // }
  122. // }
  123. // HttpContext.Current.User = new TeknikPrincipal(username);
  124. //}
  125. protected void Application_Error(object sender, EventArgs e)
  126. {
  127. Exception exception = null;
  128. try
  129. {
  130. // Get the last exception
  131. exception = Server.GetLastError();
  132. // Clear the response
  133. Response.Clear();
  134. HttpException httpException = exception as HttpException;
  135. RouteData routeData = new RouteData();
  136. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  137. routeData.DataTokens.Add("area", "Error");
  138. routeData.Values.Add("controller", "Error");
  139. routeData.Values.Add("scheme", "https");
  140. if (httpException == null)
  141. {
  142. routeData.Values.Add("action", "Exception");
  143. }
  144. else //It's an Http Exception, Let's handle it.
  145. {
  146. switch (httpException.GetHttpCode())
  147. {
  148. case 401:
  149. // Unauthorized.
  150. routeData.Values.Add("action", "Http401");
  151. break;
  152. case 403:
  153. // Forbidden.
  154. routeData.Values.Add("action", "Http403");
  155. break;
  156. case 404:
  157. // Page not found.
  158. routeData.Values.Add("action", "Http404");
  159. break;
  160. case 500:
  161. // Server error.
  162. routeData.Values.Add("action", "Http500");
  163. break;
  164. // Here you can handle Views to other error codes.
  165. // I choose a General error template
  166. default:
  167. routeData.Values.Add("action", "General");
  168. break;
  169. }
  170. }
  171. // Pass exception details to the target error View.
  172. routeData.Values.Add("exception", exception);
  173. // Clear the error on server.
  174. Server.ClearError();
  175. // Avoid IIS7 getting in the middle
  176. Response.TrySkipIisCustomErrors = true;
  177. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  178. if (new HttpRequestWrapper(Request).IsAjaxRequest())
  179. {
  180. string jsonResult = string.Empty;
  181. if (httpException == null)
  182. {
  183. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.GetFullMessage(true) } });
  184. }
  185. else
  186. {
  187. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.GetFullMessage(true) } });
  188. }
  189. Response.Write(jsonResult);
  190. }
  191. else
  192. {
  193. // Call target Controller and pass the routeData.
  194. IController errorController = new ErrorController();
  195. errorController.Execute(new RequestContext(
  196. new HttpContextWrapper(Context), routeData));
  197. }
  198. }
  199. catch (Exception ex)
  200. {
  201. // Unable to display error, so try to log it
  202. try
  203. {
  204. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Application_Error", ex);
  205. if (exception != null)
  206. {
  207. Logging.Logger.WriteEntry(Logging.LogLevel.Error, "Exception Thrown", exception);
  208. }
  209. }
  210. catch(Exception) { }
  211. }
  212. }
  213. }
  214. }