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

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