The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Global.asax.cs 9.2KB

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