public override string GetVaryByCustomString(HttpContext context, string custom) { var customs = custom.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var cacheKey = string.Empty; foreach (var type in customs) { switch (type) { case VaryByCustom.User: cacheKey += "ByUser_" + (context.User.Identity.IsAuthenticated ? context.User.Identity.Name : string.Empty); break; case VaryByCustom.UserIsAuthenticated: cacheKey += "ByUserIsAuthenticated_" + (context.User.Identity.IsAuthenticated ? "user" : "anon"); break; case VaryByCustom.Ajax: var requestBase = new HttpRequestWrapper(context.Request); cacheKey += "ByAjax_" + requestBase.IsAjaxRequest(); break; } } return(cacheKey); }
public static bool IsAjaxRequest(this HttpRequest request) { HttpRequestWrapper wrapped = new HttpRequestWrapper(request); bool isAjax = wrapped.IsAjaxRequest(); return(isAjax); }
public static void SuppressLoginRedirectsForApiCalls() { var app = HttpContext.Current.ApplicationInstance; app.PostMapRequestHandler += delegate { var ctx = HttpContext.Current; var req = new HttpRequestWrapper(ctx.Request); var handler = ctx.Handler; var isApi = (req.IsAjaxRequest() || (handler != null && handler.GetType().FullName == WebApiControllerName)); ctx.Response.SuppressFormsAuthenticationRedirect = isApi; }; var fam = FederatedAuthentication.WSFederationAuthenticationModule; if (fam != null) { fam.AuthorizationFailed += delegate(object sender, AuthorizationFailedEventArgs e) { var ctx = HttpContext.Current; if (!ctx.User.Identity.IsAuthenticated) { e.RedirectToIdentityProvider = !ctx.Response.SuppressFormsAuthenticationRedirect; } }; } }
public static void SuppressLoginRedirectsForApiCalls() { var app = HttpContext.Current.ApplicationInstance; app.PostMapRequestHandler += delegate { var ctx = HttpContext.Current; var req = new HttpRequestWrapper(ctx.Request); if (req.IsAjaxRequest()) { ctx.Response.SuppressFormsAuthenticationRedirect = true; } }; var fam = FederatedAuthentication.WSFederationAuthenticationModule; if (fam != null) { fam.AuthorizationFailed += delegate(object sender, AuthorizationFailedEventArgs e) { var ctx = HttpContext.Current; if (!ctx.User.Identity.IsAuthenticated) { e.RedirectToIdentityProvider = !ctx.Response.SuppressFormsAuthenticationRedirect; } }; } }
/// <summary> /// アプリケーションの例外イベント。 /// </summary> /// <param name="sender">イベント発生元</param> /// <param name="e">イベント引数</param> protected void Application_Error(object sender, EventArgs e) { if (Server != null) { var ex = Server.GetLastError(); if (ex != null) { // AJAX要求の場合、JSONで結果を返す var httpContext = new HttpRequestWrapper(Request); if (httpContext.IsAjaxRequest()) { Server.ClearError(); Context.Response.StatusCode = (int)HttpStatusCode.OK; Context.Response.Clear(); Context.Response.ContentType = "application/json; charset=utf-8"; Context.Response.Write(JsonConvert.SerializeObject(new { Result = false, Message = ex.Message })); Context.Response.End(); } if (ex is HttpException && ((HttpException)ex).GetHttpCode() == (int)HttpStatusCode.NotFound) { // NotFoundを相手にするとログが大変になるので無視 return; } /* * CustomErrorが無効な場合は、Controller内でおきた例外が二重にログ出力されてしまうことに注意。 * CustomErrorが有効な場合は、Controller外でおきた例外のみここでログ出力される。 */ logger.Error(ex); } } }
protected void Application_Error(object sender, EventArgs e) { var httpRequestBase = new HttpRequestWrapper(Request); if (httpRequestBase.IsAjaxRequest()) { Exception exception = Server.GetLastError(); ErrorModel errorModel = new ErrorModel( exception.GetType().FullName, exception.StackTrace, exception.Message); Response.ContentType = "application/json"; Response.Write(errorModel.ToJson()); HttpException httpException = exception as HttpException; Response.StatusCode = httpException != null ? httpException.GetHttpCode() : 500; Server.ClearError(); } }
/// <summary> /// 全局异常处理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_Error(object sender, EventArgs e) { HttpRequest request = Context.Request; StringBuilder msg = new StringBuilder() .Append(Environment.NewLine) .Append(DateTime.Now.ToShortDateString()) .Append("UserAgent: ").Append(request.UserAgent).Append(Environment.NewLine) .Append("AbsoluteUri: ").Append(request.Url.AbsoluteUri).Append(Environment.NewLine) .Append("UrlReferrer: ").Append(request.UrlReferrer).Append(Environment.NewLine) .Append("Exception: ").Append(Server.GetLastError()).Append(Environment.NewLine) .Append("-------------------------------------------------------------------------------").Append(Environment.NewLine); //Logger.Default.Error(msg.ToString()); bool iserrorview = true; if (iserrorview) //是否开启错误视图 { var lastError = Server.GetLastError(); if (lastError != null) { var httpError = lastError as HttpException; if (httpError != null) { //400与404错误不记录日志,并都以自定义404页面响应 var httpCode = httpError.GetHttpCode(); if (httpCode == 400 || httpCode == 404) { Response.StatusCode = 404; Server.ClearError(); Response.Redirect("/Error_404.html", true); return; } } //对于路径错误不记录日志,并都以自定义404页面响应 if (lastError.TargetSite.ReflectedType == typeof(System.IO.Path)) { Response.StatusCode = 404; Server.ClearError(); Response.Redirect("/Error_404.html"); return; } Response.StatusCode = 500; Server.ClearError(); var httprequestwrapper = new HttpRequestWrapper(request); if (!httprequestwrapper.IsAjaxRequest()) { Response.Redirect("/Error_500.html", true); } } } }
private void Context_BeginRequest(object sender, EventArgs e) { var context = HttpContext.Current; var request = new HttpRequestWrapper(context.Request); if (!request.IsAjaxRequest()) { // currently we only care about ajax requests since full page loads will go through the normal CMS pipeline return; } GigyaAccountHelper.ProcessRequestChecks(context); }
private void CheckForAuthFailure(object sender, EventArgs e) { var app = sender as HttpApplication; var response = new HttpResponseWrapper(app.Response); var request = new HttpRequestWrapper(app.Request); var context = new HttpContextWrapper(app.Context); if (true.Equals(context.Items["RequestWasNotAuthorized"]) && request.IsAjaxRequest()) { response.StatusCode = 401; response.ClearContent(); } }
protected void Application_BeginRequest(Object sender, EventArgs e) { //输入Portal转向到Index.html页面 if (Context.Request.FilePath == "/Cluster" || Context.Request.FilePath == "/Cluster/") { Context.Response.Redirect("/Cluster/login.html"); } HttpRequestBase request = new HttpRequestWrapper(this.Context.Request); //ajax请求,取消FormsAuthenticationRedirect. if (request.IsAjaxRequest()) { Context.Response.SuppressFormsAuthenticationRedirect = true; } }
protected void Application_BeginRequest(Object sender, EventArgs e) { //输入Portal转向到Index.html页面 if (Context.Request.FilePath == AppUtility.PortalRoot || Context.Request.FilePath == AppUtility.PortalRoot + "/") { AppUtility.Engine.LogWriter.Write("Request Path:" + Context.Request.RawUrl); Context.Response.Redirect(AppUtility.PortalRoot + "/index.html"); } HttpRequestBase request = new HttpRequestWrapper(this.Context.Request); //ajax请求,取消FormsAuthenticationRedirect. if (request.IsAjaxRequest()) { Context.Response.SuppressFormsAuthenticationRedirect = true; } }
private void Application_Error(object sender, EventArgs e) { var lastError = Server.GetLastError(); if (lastError != null) { var httpError = lastError as HttpException; if (httpError != null) { var httpCode = httpError.GetHttpCode().ToString(); var httpResutWrapper = new HttpRequestWrapper(System.Web.HttpContext.Current.Request); if (httpResutWrapper.IsAjaxRequest() && httpResutWrapper.HttpMethod.ToLower() == "post") { httpCode = "AjaxPost"; } } } }
protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); var httpContext = ((HttpApplication)sender).Context; var httpRequest = new HttpRequestWrapper(Request); httpContext.Response.Clear(); httpContext.ClearError(); httpContext.Response.TrySkipIisCustomErrors = true; if (httpRequest.IsAjaxRequest()) { Response.ContentType = "application/json"; Response.StatusCode = 400; Response.Write( JsonConvert.SerializeObject(new { erros = new[] { new { ErrorMessage = exception.Message } } })); } else { var rota = new RouteData(); rota.Values["Controller"] = "Home"; rota.Values["Action"] = "Erro"; HttpContext.Current.Session["LastException"] = exception.Message; HttpContext.Current.Session["LastStackTrace"] = exception.StackTrace; httpContext.Response.RedirectToRoute("Default", rota.Values); } }
private void Application_Error(object sender, EventArgs e) { //处理错误信息SDK var lastError = Server.GetLastError(); if (lastError != null) { var httpError = lastError as HttpException; if (httpError != null) { var httpCode = httpError.GetHttpCode().ToString(); var httpResutWrapper = new HttpRequestWrapper(System.Web.HttpContext.Current.Request); //判断当前请求是否为Ajax并且方式为Get if (httpResutWrapper.IsAjaxRequest() && httpResutWrapper.HttpMethod.ToLower() == "post") { httpCode = "AjaxPost"; } //HttpContext.Current.Response.Redirect(string.Format("~/Errors/Error{0}", httpCode)); //Server.ClearError(); } } }
public static void SuppressLoginRedirectsForApiCalls() { var sam = FederatedAuthentication.WSFederationAuthenticationModule; if (sam != null) { sam.AuthorizationFailed += delegate(object sender, AuthorizationFailedEventArgs e) { var ctx = HttpContext.Current; if (!ctx.Request.IsAuthenticated) { var handler = ctx.Handler; var req = new HttpRequestWrapper(ctx.Request); var isApi = (req.IsAjaxRequest() || (handler != null && handler.GetType().FullName == WebApiControllerName)); e.RedirectToIdentityProvider = !isApi; } }; } }
/// <summary> /// 页面请求开始 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_BeginRequest(Object sender, EventArgs e) { // 输入Portal转向到Index.html页面 if (Context.Request.FilePath == AppUtility.PortalRoot || Context.Request.FilePath == AppUtility.PortalRoot + "/") { if (OThinker.H3.Controllers.AppConfig.ConnectionMode == ConnectionStringParser.ConnectionMode.Mono) { AppUtility.Engine.LogWriter.Write("Request Path:" + Context.Request.RawUrl); Context.Response.Redirect(AppUtility.PortalRoot + "/index.html"); } } HttpRequestBase request = new HttpRequestWrapper(this.Context.Request); // ajax请求,取消FormsAuthenticationRedirect. if (request.IsAjaxRequest()) { Context.Response.SuppressFormsAuthenticationRedirect = true; } if (Context.Request.Url.ToString().IndexOf("ThreadAdmin", StringComparison.OrdinalIgnoreCase) == -1) { AddCurrentThread(); } }
private static void OnError(object sender, EventArgs e) { if (HostingEnvironment.IsDevelopmentEnvironment) { return; } var application = (HttpApplication)sender; var context = application.Context; var request = new HttpRequestWrapper(context.Request); var server = application.Server; var exception = server.GetLastError(); if (exception == null) { return; } LogHelpers.Write(exception); var httpException = exception as HttpException ?? new HttpException(null, exception); var errorInfo = new ErrorHandlingModel { HttpCode = (HttpStatusCode)httpException.GetHttpCode(), ErrorMessage = httpException.Message, RequestUrl = request.Url, IsAjaxRequest = request.IsAjaxRequest(), HttpMethod = request.HttpMethod }; var result = RedirectionResult.Value(errorInfo); server.ClearError(); context.ExecuteAction(result); }
protected void Application_Error(object sender, EventArgs args) { try { var exception = Server.GetLastError(); var request = new HttpRequestWrapper(HttpContext.Current.Request); var isAjax = request.IsAjaxRequest(); var httpException = exception as HttpException; if (httpException != null) { if (httpException.GetHttpCode() == 404) { if (!isAjax) { using (var controller = new HomeController()) { var controllerContext = new ControllerContext(HttpContext.Current.Request.RequestContext, controller); var result = new ViewResult { ViewName = "~/Views/Errors/Error404.cshtml" }; result.ExecuteResult(controllerContext); HttpContext.Current.Response.End(); } return; } } } if (isAjax && request.IsSmartBlocksRequest()) { HandleException(exception); using (var controller = new HomeController()) { var controllerContext = new ControllerContext(HttpContext.Current.Request.RequestContext, controller); var result = controller.GetErrorJsonResponse(exception); result.ExecuteResult(controllerContext); HttpContext.Current.Response.End(); } return; } HandleException(exception); using (var controller = new HomeController()) { var controllerContext = new ControllerContext(HttpContext.Current.Request.RequestContext, controller); var result = new ViewResult { ViewName = "~/Views/Errors/Error.cshtml", ViewData = { Model = new ErrorModel() { Exception = exception, IsAjax = isAjax } } }; result.ExecuteResult(controllerContext); HttpContext.Current.Response.End(); } } catch (Exception exception) { LogManager.GetCurrentClassLogger().Fatal(exception); } }