The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Global.asax.cs 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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.Migrations;
  12. using System.Data.Entity.Migrations;
  13. using Teknik.Areas.Profile.Models;
  14. using System.ComponentModel;
  15. using Teknik.Areas.Error.Controllers;
  16. using System.Web.Helpers;
  17. using System.Diagnostics;
  18. using System.Collections.Specialized;
  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. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  30. RouteConfig.RegisterRoutes(RouteTable.Routes);
  31. BundleConfig.RegisterBundles(BundleTable.Bundles);
  32. }
  33. protected void Application_BeginRequest(object sender, EventArgs e)
  34. {
  35. HttpContext context = HttpContext.Current;
  36. var stopwatch = new Stopwatch();
  37. HttpContext.Current.Items["Stopwatch"] = stopwatch;
  38. stopwatch.Start();
  39. }
  40. protected void Application_EndRequest(object sender, EventArgs e)
  41. {
  42. HttpContext context = HttpContext.Current;
  43. Stopwatch stopwatch = (Stopwatch)context.Items["Stopwatch"];
  44. stopwatch.Stop();
  45. TimeSpan ts = stopwatch.Elapsed;
  46. string elapsedTime = String.Format("{0} seconds", ts.TotalSeconds);
  47. context.Response.AppendHeader("GenerationTime", elapsedTime);
  48. // Allow this domain
  49. string origin = context.Request.Headers.Get("Origin");
  50. if (!string.IsNullOrEmpty(origin))
  51. context.Response.AppendHeader("Access-Control-Allow-Origin", origin);
  52. }
  53. protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
  54. {
  55. if (FormsAuthentication.CookiesSupported == true)
  56. {
  57. if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
  58. {
  59. //let us take out the username now
  60. string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
  61. List<string> roles = new List<string>();
  62. using (TeknikEntities entities = new TeknikEntities())
  63. {
  64. User user = entities.Users.Include("Groups").Include("Groups.Roles").SingleOrDefault(u => u.Username == username);
  65. if (user != null)
  66. {
  67. foreach (Group grp in user.Groups)
  68. {
  69. foreach (Role role in grp.Roles)
  70. {
  71. if (!roles.Contains(role.Name))
  72. {
  73. roles.Add(role.Name);
  74. }
  75. }
  76. }
  77. }
  78. }
  79. //Let us set the Pricipal with our user specific details
  80. HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
  81. new System.Security.Principal.GenericIdentity(username, "Forms"), roles.ToArray());
  82. }
  83. }
  84. }
  85. protected void Application_Error(object sender, EventArgs e)
  86. {
  87. Exception exception = Server.GetLastError();
  88. Response.Clear();
  89. HttpException httpException = exception as HttpException;
  90. RouteData routeData = new RouteData();
  91. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  92. routeData.DataTokens.Add("area", "Error");
  93. routeData.Values.Add("controller", "Error");
  94. if (httpException == null)
  95. {
  96. routeData.Values.Add("action", "Exception");
  97. }
  98. else //It's an Http Exception, Let's handle it.
  99. {
  100. switch (httpException.GetHttpCode())
  101. {
  102. case 401:
  103. // Unauthorized.
  104. routeData.Values.Add("action", "Http401");
  105. break;
  106. case 403:
  107. // Forbidden.
  108. routeData.Values.Add("action", "Http403");
  109. break;
  110. case 404:
  111. // Page not found.
  112. routeData.Values.Add("action", "Http404");
  113. break;
  114. case 500:
  115. // Server error.
  116. routeData.Values.Add("action", "Http500");
  117. break;
  118. // Here you can handle Views to other error codes.
  119. // I choose a General error template
  120. default:
  121. routeData.Values.Add("action", "General");
  122. break;
  123. }
  124. }
  125. // Pass exception details to the target error View.
  126. routeData.Values.Add("exception", exception);
  127. // Clear the error on server.
  128. Server.ClearError();
  129. // Avoid IIS7 getting in the middle
  130. Response.TrySkipIisCustomErrors = true;
  131. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  132. if (IsAjaxRequest())
  133. {
  134. string jsonResult = string.Empty;
  135. if (httpException == null)
  136. {
  137. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.Message } });
  138. }
  139. else
  140. {
  141. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.Message } });
  142. }
  143. Response.Write(jsonResult);
  144. }
  145. else
  146. {
  147. // Call target Controller and pass the routeData.
  148. IController errorController = new ErrorController();
  149. errorController.Execute(new RequestContext(
  150. new HttpContextWrapper(Context), routeData));
  151. }
  152. }
  153. //This method checks if we have an AJAX request or not
  154. private bool IsAjaxRequest()
  155. {
  156. //The easy way
  157. bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
  158. || ((Request.Headers != null)
  159. && (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
  160. //If we are not sure that we have an AJAX request or that we have to return JSON
  161. //we fall back to Reflection
  162. if (!isAjaxRequest)
  163. {
  164. try
  165. {
  166. //The controller and action
  167. string controllerName = Request.RequestContext.
  168. RouteData.Values["controller"].ToString();
  169. string actionName = Request.RequestContext.
  170. RouteData.Values["action"].ToString();
  171. //We create a controller instance
  172. DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
  173. Controller controller = controllerFactory.CreateController(
  174. Request.RequestContext, controllerName) as Controller;
  175. //We get the controller actions
  176. ReflectedControllerDescriptor controllerDescriptor =
  177. new ReflectedControllerDescriptor(controller.GetType());
  178. ActionDescriptor[] controllerActions =
  179. controllerDescriptor.GetCanonicalActions();
  180. //We search for our action
  181. foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
  182. {
  183. if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
  184. {
  185. //If the action returns JsonResult then we have an AJAX request
  186. if (actionDescriptor.MethodInfo.ReturnType
  187. .Equals(typeof(JsonResult)))
  188. return true;
  189. }
  190. }
  191. }
  192. catch
  193. {
  194. }
  195. }
  196. return isAjaxRequest;
  197. }
  198. }
  199. }