/// <summary> /// 发送异常页面通知 /// </summary> /// <param name="exception">异常</param> private void SendErrorPage(Exception exception) { var httpException = exception as HttpException; var response = HttpContext.Current.Response; response.Status = httpException != null ? httpException.Code : HttpStatusCode.InternalServerError; response.Reason = exception.Message; if (response.Body.CanWrite) response.Body.SetLength(0); var args = new ErrorPageEventArgs(HttpContext.Current) { Exception = exception }; // 发送异常错误页面请求事件通知 ErrorPageRequested(this, args); try { var generator = new ResponseWriter(); if (args.IsHandled) generator.Send(HttpContext.Current, response); else generator.SendErrorPage(HttpContext.Current, response, exception); } catch (Exception err) { Logger.Error("Failed to display error page"); ExceptionHandler.Handle(err); } }
/// <summary> /// 响应上下文中接收请求消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnContextRequest(object sender, RequestEventArgs e) { var context = (HttpContext)sender; HttpFactory.Current = Factory; HttpContext.Current = context; try { var args = new RequestEventArgs(context, e.Request, e.Response); // 触发请求收到事件通知 RequestReceived(this, args); // 判断外部程序是否已处理该请求 if (!args.IsHandled) { // 如果外部程序未处理该请求,则发送请求的响应消息 var generator = new ResponseWriter(); generator.Send(context, args.Response); } // 请求被处理后断开连接 if (e.Response.HttpVersion == "HTTP/1.0" || e.Response.Connection.Type == ConnectionType.Close) context.Disconnect(); } catch (Exception err) { if (err is HttpException) { var exception = (HttpException)err; SendErrorPage(exception); } else { Logger.Debug("Request failed."); ExceptionHandler.Handle(err); SendErrorPage(err); } e.IsHandled = true; } }