public void StaticMethods_Deny_Unrestricted()
 {
     Assert.AreEqual(-1, HttpWorkerRequest.GetKnownRequestHeaderIndex("mono"), "GetKnownRequestHeaderIndex");
     Assert.AreEqual("Cache-Control", HttpWorkerRequest.GetKnownRequestHeaderName(0), "GetKnownRequestHeaderName");
     Assert.AreEqual(-1, HttpWorkerRequest.GetKnownResponseHeaderIndex("mono"), "GetKnownResponseHeaderIndex");
     Assert.AreEqual("Cache-Control", HttpWorkerRequest.GetKnownResponseHeaderName(0), "GetKnownResponseHeaderName");
     Assert.AreEqual("OK", HttpWorkerRequest.GetStatusDescription(200), "GetStatusDescription");
 }
示例#2
0
        public static string FormatErrorMessageBody(int statusCode, string appName)
        {
            string desc = HttpWorkerRequest.GetStatusDescription(statusCode);

            return(string.Format(_httpErrorFormat1, desc)
                   + _httpStyle
                   + string.Format(_httpErrorFormat2, appName, statusCode, desc));
        }
示例#3
0
        /// <summary>
        /// Returns the standard HTTP request header that corresponds to the specified index.
        /// </summary>
        /// <returns>The HTTP request header.</returns>
        /// <param name="index">The index of the header. For example, the <see cref="F:System.Web.HttpWorkerRequest.HeaderAllow" /> field. </param>
        public override string GetKnownRequestHeader(int index)
        {
            string name = HttpWorkerRequest.GetKnownRequestHeaderName(index);

            string[] value = null;
            this.context.Request.Headers.TryGetValue(name, out value);
            return(value != null && value.Length > 0 ? value[0] : null);
        }
        private void ReadAll(HttpWorkerRequest worker)
        {
            // Check if body contains data
            if (!worker.HasEntityBody())
            {
                return;
            }

            // Get the initial bytes loaded
            byte[] initbits = worker.GetPreloadedEntityBody();
            if (worker.IsEntireEntityBodyIsPreloaded())
            {
                // Nothing more to read
                return;
            }

            // Get the total body length
            int requestLength = worker.GetTotalEntityBodyLength();
            int initialBytes  = (initbits != null) ? initbits.Length : 4096;
            int receivedBytes = initialBytes;

            byte[] buffer = new byte[512 * 1024];

            // We get a negative length in case of very large files.

            if (requestLength < 0)
            {
                // This code is slower than the else part, although it does the same thing.
                // We need to do it differently to handle negative content length

                try
                {
                    do
                    {
                        // Read another set of bytes
                        initialBytes = worker.ReadEntityBody(buffer, buffer.Length);

                        // Update the received bytes
                        receivedBytes += initialBytes;
                    } while (initialBytes != 0);
                }
                catch
                {
                }
            }
            else
            {
                while (requestLength - receivedBytes >= initialBytes)
                {
                    // Read another chunk of bytes
                    initialBytes   = worker.ReadEntityBody(buffer, buffer.Length);
                    receivedBytes += initialBytes;
                }

                // Read remaining part if any
                initialBytes = worker.ReadEntityBody(buffer, (int)(requestLength - receivedBytes));
            }
        }
        // This constructor creates the header collection for response headers.
        // Try to preallocate the base collection with a size that should be sufficient
        // to store the headers for most requests.
        internal HttpHeaderCollection(HttpWorkerRequest wr, HttpResponse response, int capacity)
            : base(capacity)
        {
            // if this is an IIS7WorkerRequest, then the collection will be writeable and we will
            // call into IIS7 to update the header blocks when changes are made.
            _iis7WorkerRequest = wr as IIS7WorkerRequest;

            _response = response;
        }
        private static void PublishCounters(HttpWorkerRequest httpWorkerRequest, RequestLogger logger)
        {
            string serverVariable = httpWorkerRequest.GetServerVariable(NativeProxyLogHelper.NativeProxyStatisticsVariables.Counters);

            if (!string.IsNullOrEmpty(serverVariable))
            {
                logger.AppendGenericInfo(NativeProxyLogHelper.NativeProxyStatisticsVariables.Counters, serverVariable);
            }
        }
示例#7
0
        public static string FormatErrorMessageBody(int statusCode, string appName)
        {
            string statusDescription = HttpWorkerRequest.GetStatusDescription(statusCode);
            string text  = string.Format("服务器出错 发生在 '{0}' Web应用程序中.", appName);
            string text2 = string.Format("HTTP错误 {0} - {1}.", statusCode, statusDescription);

            return(string.Format(CultureInfo.InvariantCulture, m_httpErrorFormat1, statusDescription) + m_httpStyle
                   + string.Format(CultureInfo.InvariantCulture, Messages.m_httpErrorFormat2, text, text2, m_versionInfo));
        }
示例#8
0
 protected virtual void SetStatusCode(HttpResponseBase response)
 {
     if (this.StatusCode != HttpStatusCode.OK)
     {
         int statusCode = (int)this.StatusCode;
         response.StatusCode        = statusCode;
         response.StatusDescription = HttpWorkerRequest.GetStatusDescription(statusCode);
     }
 }
        private static void PublishGenericStats(HttpWorkerRequest httpWorkerRequest, RequestLogger logger, string statsDataName)
        {
            string serverVariable = httpWorkerRequest.GetServerVariable(statsDataName);

            if (!string.IsNullOrEmpty(serverVariable))
            {
                logger.AppendGenericInfo(statsDataName, serverVariable);
            }
        }
示例#10
0
        public override void SendKnownResponseHeader(int index, string value)
        {
            string knownResponseHeaderName = HttpWorkerRequest.GetKnownResponseHeaderName(index);

            if (!string.IsNullOrEmpty(knownResponseHeaderName))
            {
                this.SendUnknownResponseHeader(knownResponseHeaderName, value);
            }
        }
示例#11
0
        public static string FormatErrorMessageBody(int statusCode, string appName)
        {
            string statusDescription = HttpWorkerRequest.GetStatusDescription(statusCode);

            return
                (string.Format("<html><head><title>{0}</title>", statusDescription) +
                 "<style>body {font-family:\"Verdana\";font-weight:normal;font-size: 8pt;color:black;}p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}h1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }h2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }pre {font-family:\"Lucida Console\";font-size: 8pt}.marker {font-weight: bold; color: black;text-decoration: none;}.version {color: gray;}.error {margin-bottom: 10px;}.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }</style>" +
                 string.Format(_httpErrorFormat2, appName, statusCode, statusDescription));
        }
示例#12
0
        // This constructor creates the header collection for response headers.
        // Try to preallocate the base collection with a size that should be sufficient
        // to store the headers for most requests.
        internal HttpHeaderCollection(HttpWorkerRequest wr, HttpResponse response, int capacity)
            : base(capacity)
        {
            // if this is an IIS7WorkerRequest, then the collection will be writeable and we will
            // call into IIS7 to update the header blocks when changes are made.
            _iis7WorkerRequest = wr as IIS7WorkerRequest;

            _response = response;
        }
示例#13
0
        ///// <summary>
        ///// Called when a new request commences (but after authentication).
        ///// Preloads the request header and initialises the form stream.
        /////
        ///// We do this after authentication so that the file processor will
        ///// have access to the security context if it is required.
        ///// </summary>
        ///// <param name="sender">Sender.</param>
        ///// <param name="e">Event args.</param>
        //void Context_AuthenticateRequest(object sender, EventArgs e)
        //{
        //    HttpApplication app = sender as HttpApplication;
        //    HttpWorkerRequest worker = GetWorkerRequest(app.Context);
        //    int bufferSize;
        //    string boundary;
        //    string ct;
        //    bool statusPersisted = false;

        //    bufferSize = UploadManager.Instance.BufferSize;

        //    ct = worker.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType);

        //    // Is this a multi-part form which may contain file uploads?
        //    if (ct != null && string.Compare(ct, 0, C_MARKER, 0, C_MARKER.Length, true, CultureInfo.InvariantCulture) == 0)
        //    {
        //        // Get the content length from the header. Don't use Request.ContentLength as this is cached
        //        // and we don't want it to be calculated until we're done stripping out the files.
        //        long length = long.Parse(worker.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));

        //        if (length > 0)
        //        {
        //            if (length / 1024 > GetMaxRequestLength(app.Context))
        //            {
        //                // End the request if the maximum request length is exceeded.
        //                EndRequestOnRequestLengthExceeded(app.Context.Response);
        //                return;
        //            }

        //            boundary = "--" + ct.Substring(ct.IndexOf(B_MARKER) + B_MARKER.Length);

        //            InitStatus(length);

        //            using (FormStream fs = new FormStream(GetProcessor(), boundary, app.Request.ContentEncoding))
        //            {
        //                // Set up events
        //                fs.FileCompleted += new FileEventHandler(fs_FileCompleted);
        //                fs.FileCompletedError += new FileErrorEventHandler(fs_FileCompletedError);
        //                fs.FileStarted += new FileEventHandler(fs_FileStarted);

        //                byte[] data = null;
        //                int read = 0;
        //                int counter = 0;

        //                if (worker.GetPreloadedEntityBodyLength() > 0)
        //                {
        //                    // Read the first portion of data from the client
        //                    data = worker.GetPreloadedEntityBody();

        //                    fs.Write(data, 0, data.Length);

        //                    if (!String.IsNullOrEmpty(fs.StatusKey))
        //                    {
        //                        if (!statusPersisted) PersistStatus(fs.StatusKey);
        //                        statusPersisted = true;
        //                        _status.UpdateBytes(data.Length, _processor.GetFileName(), _processor.GetIdentifier());
        //                    }

        //                    counter = data.Length;
        //                }

        //                bool disconnected = false;

        //                // Read data
        //                while (counter < length && worker.IsClientConnected() && !disconnected)
        //                {
        //                    if (counter + bufferSize > length)
        //                    {
        //                        bufferSize = (int)length - counter;
        //                    }

        //                    data = new byte[bufferSize];
        //                    read = worker.ReadEntityBody(data, bufferSize);

        //                    if (read > 0)
        //                    {
        //                        counter += read;
        //                        fs.Write(data, 0, read);

        //                        if (!String.IsNullOrEmpty(fs.StatusKey))
        //                        {
        //                            if (!statusPersisted) PersistStatus(fs.StatusKey);
        //                            statusPersisted = true;
        //                            _status.UpdateBytes(counter, _processor.GetFileName(), _processor.GetIdentifier());
        //                        }
        //                    }
        //                    else
        //                    {
        //                        disconnected = true;
        //                    }
        //                }

        //                if (!worker.IsClientConnected() || disconnected)
        //                {
        //                    app.Context.Response.End();
        //                    return;
        //                }

        //                if (fs.ContentMinusFiles != null)
        //                {
        //                    BindingFlags ba = BindingFlags.Instance | BindingFlags.NonPublic;

        //                    // Replace the worker process with our own version using reflection
        //                    UploadWorkerRequest wr = new UploadWorkerRequest(worker, fs.ContentMinusFiles);
        //                    app.Context.Request.GetType().GetField("_wr", ba).SetValue(app.Context.Request, wr);
        //                }

        //                // Check that the query key is in the request
        //                app.Context.Items[UploadManager.STATUS_KEY] = fs.StatusKey;
        //            }
        //        }

        //    }
        //}

        void Context_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication   application   = (HttpApplication)sender;
            HttpContext       context       = application.Context;
            IServiceProvider  provider      = (IServiceProvider)context;
            HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

            var ct = workerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType);

            //    // Is this a multi-part form which may contain file uploads?
            if (ct != null && string.Compare(ct, 0, C_MARKER, 0, C_MARKER.Length, true, CultureInfo.InvariantCulture) == 0)
            {
                HttpRequest request = context.Request;
                if (request.Files.Count > 0)
                {
                    foreach (string key in request.Files.Keys)
                    {
                        FileStream fs = null;
                        // Check if body contains data
                        //  if (workerRequest.HasEntityBody())
                        {
                            // get the total body length
                            //  int requestLength = workerRequest.GetTotalEntityBodyLength();

                            //    if (!workerRequest.IsEntireEntityBodyIsPreloaded())
                            {
                                byte[] buffer        = new byte[512000];
                                string fileName      = request.Files[key].FileName;//context.Request.QueryString["fileName"].Split(new char[] { '\\' });
                                int    requestLength = request.Files[key].ContentLength;
                                var    uploadFolder  = ConfigurationManager.AppSettings["TemporaryUploadFolder"];

                                Console.WriteLine("Starting Download " + DateTime.Now.ToString(CultureInfo.InvariantCulture));

                                fs = new FileStream(context.Server.MapPath(uploadFolder + fileName), FileMode.Create);
                                // Set the received bytes to initial bytes before start reading
                                int initialBytes  = 0;
                                int receivedBytes = initialBytes;
                                while (requestLength - receivedBytes >= initialBytes)
                                {
                                    // Read another set of bytes
                                    initialBytes = request.Files[key].InputStream.Read(buffer, 0, buffer.Length);
                                    //    request.Files[key].ContentType); //workerRequest.ReadEntityBody(buffer, buffer.Length);
                                    // Write the chunks to the physical file
                                    fs.Write(buffer, 0, buffer.Length);
                                    // Update the received bytes
                                    receivedBytes += initialBytes;
                                    Console.WriteLine("Saving file " + receivedBytes / requestLength + " bytes downloaded @ " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                                }
                                initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
                            }
                        }
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
        }
示例#14
0
        public void ProcessRequest(HttpContext context)
        {
            IServiceProvider  provider = context as IServiceProvider;
            HttpWorkerRequest workRqst = provider.GetService(typeof(HttpWorkerRequest)) as HttpWorkerRequest;
            int rqstLen = workRqst.GetPreloadedEntityBodyLength();
            int totLen  = workRqst.GetTotalEntityBodyLength();

            byte[] buffer = new byte[1024];
            workRqst.ReadEntityBody(buffer, 0, buffer.Length);
        }
示例#15
0
文件: MyHost.cs 项目: raj581/Marvin
        public static WebTest GetCurrentTest()
        {
            HttpWorkerRequest hwr = GetMyWorkerRequest();

            if (hwr == null)
            {
                return(null);
            }
            return(GetMyData(hwr).currentTest);
        }
示例#16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>+
        /// <param name="e"></param>
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            IServiceProvider  isp    = (IServiceProvider)HttpContext.Current;
            HttpWorkerRequest worker = (HttpWorkerRequest)isp.GetService(typeof(HttpWorkerRequest));

            byte[] buffer = worker.GetPreloadedEntityBody();
            if (!worker.IsEntireEntityBodyIsPreloaded())
            {
            }
        }
示例#17
0
        public override string GetKnownRequestHeader(int index)
        {
            if ((this._reqData.RequestHttpHeader == null) || (this._reqData.RequestHttpHeader.Count < 1))
            {
                return("");
            }
            string knownRequestHeaderName = HttpWorkerRequest.GetKnownRequestHeaderName(index);

            return(this.GetUnknownRequestHeader(knownRequestHeaderName));
        }
示例#18
0
        //- @FormatErrorMessageBody- //
        public static String FormatErrorMessageBody(Int32 statusCode, String appName)
        {
            String statusDescription = HttpWorkerRequest.GetStatusDescription(statusCode);
            String text1             = String.Format("Server Error in '{0}' Application.", appName);
            String text2             = String.Format("HTTP Error {0} - {1}.", statusCode, statusDescription);
            String text3             = "Version Information";
            String text4             = "NetFXHarmonics DevServer";

            return(String.Format(CultureInfo.InvariantCulture, "<html>\r\n    <head>\r\n        <title>{0}</title>\r\n", new Object[] { statusDescription }) + "        <style>\r\n        \tbody {font-family:\"Verdana\";font-weight:normal;font-size: 8pt;color:black;} \r\n        \tp {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n        \tb {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n        \th1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n        \th2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n        \tpre {font-family:\"Lucida Console\";font-size: 8pt}\r\n        \t.marker {font-weight: bold; color: black;text-decoration: none;}\r\n        \t.version {color: gray;}\r\n        \t.error {margin-bottom: 10px;}\r\n        \t.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }\r\n        </style>\r\n" + String.Format(CultureInfo.InvariantCulture, _httpErrorFormat2, new Object[] { text1, text2, text3, text4 }));
        }
        /// <summary>
        /// Sets status code and description.
        /// </summary>
        /// <param name="context">The <see cref="IHttpListenerContext" /> to send the response through.</param>
        /// <param name="statusCode">The HTTP status code for the response.</param>
        /// <exception cref="System.ArgumentNullException">context</exception>
        /// <exception cref="ArgumentNullException"><paramref name="context" /> is <c>null</c>.</exception>
        public static void SetStatusCode(this IWebDavContext context, int statusCode)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Response.StatusCode        = statusCode;
            context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription(statusCode);
        }
        public static KeyValuePair <HttpContext, HttpApplicationStub> GetContext(HttpWorkerRequest wr, params IHttpModule[] modules)
        {
            var ctx = new HttpContext(wr);
            var app = new HttpApplicationStub(modules);

            SetHttpApplicationFactoryCustomApplication(app);
            InitInternal(app, ctx);
            AssignContext(app, ctx);
            return(new KeyValuePair <HttpContext, HttpApplicationStub>(ctx, app));
        }
示例#21
0
 protected DecoratedWorkerRequest(HttpWorkerRequest origWorker)
 {
     if (log.IsDebugEnabled)
     {
         log.Debug("origWorker=" + origWorker);
     }
     OrigWorker = origWorker;
     // Remember the original HttpContext so that it can be used by UploadHttpModule.AppendToLog().
     OrigContext = HttpContext.Current;
 }
示例#22
0
 private Type GetKnownWorkerRequestType(HttpWorkerRequest workerRequest)
 {
     return(workerRequest.GetType());
     //Type baseType = workerRequest.GetType();
     //while ((((baseType != null) && (baseType.FullName != "System.Web.Hosting.ISAPIWorkerRequest")) && (baseType.FullName != "Cassini.Request")) && (baseType.FullName != "Microsoft.VisualStudio.WebHost.Request"))
     //{
     //    baseType = baseType.BaseType;
     //}
     //return baseType;
 }
示例#23
0
        private void SendNegotiationErrorResponse(StreamWriter writer, HttpStatusCode code)
        {
            Int32 intCode = (Int32)code;

            writer.Write("HTTP/1.1 ");
            writer.Write(intCode);
            writer.Write(" ");
            writer.Write(HttpWorkerRequest.GetStatusDescription(intCode));
            writer.Write("\r\n\r\n");
        }
示例#24
0
        /// <summary>
        /// This Method running at Global.asax To Cath MaxRequestException
        /// and Redirect the user to RedirectPage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="RedirectPage"></param>
        public static void CatchMaxRequestLength(HttpApplication sender, string RedirectPage)
        {
            HttpRuntimeSection runTime = (HttpRuntimeSection)
                                         WebConfigurationManager.GetSection("system.web/httpRuntime");

            //Approx 100 Kb(for page content) size has been deducted because
            //the maxRequestLength proprty is the page size, not only the file upload size
            int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

            //This code is used to check the request length of the page
            //and if the request length is greater than MaxRequestLength then retrun
            //to the same page with extra query string value action=exception
            HttpContext context = sender.Context;

            if (context.Request.ContentLength > maxRequestLength)
            {
                IServiceProvider provider = (IServiceProvider)context;

                HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

                // Check if body contains data
                if (workerRequest.HasEntityBody())
                {
                    // get the total body length
                    int requestLength = workerRequest.GetTotalEntityBodyLength();

                    // Get the initial bytes loaded
                    int initialBytes = 0;

                    if (workerRequest.GetPreloadedEntityBody() != null)
                    {
                        initialBytes = workerRequest.GetPreloadedEntityBody().Length;
                    }

                    if (!workerRequest.IsEntireEntityBodyIsPreloaded())
                    {
                        byte[] buffer = new byte[512000];

                        // Set the received bytes to initial bytes before start reading
                        int receivedBytes = initialBytes;

                        while (requestLength - receivedBytes >= initialBytes)
                        {
                            // Read another set of bytes
                            initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);

                            // Update the received bytes
                            receivedBytes += initialBytes;
                        }
                        initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
                    }
                }
                context.Response.Redirect(RedirectPage);
            }
        }
示例#25
0
        private static CachedRawResponse Convert(OutputCacheEntry oce)
        {
            ArrayList headers = null;

            if ((oce.HeaderElements != null) && (oce.HeaderElements.Count > 0))
            {
                headers = new ArrayList(oce.HeaderElements.Count);
                for (int i = 0; i < oce.HeaderElements.Count; i++)
                {
                    HttpResponseHeader header = new HttpResponseHeader(oce.HeaderElements[i].Name, oce.HeaderElements[i].Value);
                    headers.Add(header);
                }
            }
            ArrayList buffers = null;

            if ((oce.ResponseElements != null) && (oce.ResponseElements.Count > 0))
            {
                buffers = new ArrayList(oce.ResponseElements.Count);
                for (int j = 0; j < oce.ResponseElements.Count; j++)
                {
                    ResponseElement      element  = oce.ResponseElements[j];
                    IHttpResponseElement element2 = null;
                    if (element is FileResponseElement)
                    {
                        HttpContext       current     = HttpContext.Current;
                        HttpWorkerRequest request     = (current != null) ? current.WorkerRequest : null;
                        bool supportsLongTransmitFile = (request != null) && request.SupportsLongTransmitFile;
                        bool isImpersonating          = ((current != null) && current.IsClientImpersonationConfigured) || HttpRuntime.IsOnUNCShareInternal;
                        FileResponseElement element3  = (FileResponseElement)element;
                        element2 = new HttpFileResponseElement(element3.Path, element3.Offset, element3.Length, isImpersonating, supportsLongTransmitFile);
                    }
                    else if (element is MemoryResponseElement)
                    {
                        MemoryResponseElement element4 = (MemoryResponseElement)element;
                        int size = System.Convert.ToInt32(element4.Length);
                        element2 = new HttpResponseBufferElement(element4.Buffer, size);
                    }
                    else
                    {
                        if (!(element is SubstitutionResponseElement))
                        {
                            throw new NotSupportedException();
                        }
                        SubstitutionResponseElement element5 = (SubstitutionResponseElement)element;
                        element2 = new HttpSubstBlockResponseElement(element5.Callback);
                    }
                    buffers.Add(element2);
                }
            }
            else
            {
                buffers = new ArrayList();
            }
            return(new CachedRawResponse(new HttpRawResponse(oce.StatusCode, oce.StatusDescription, headers, buffers, false), oce.Settings, oce.KernelCacheUrl, oce.CachedVaryId));
        }
示例#26
0
        public ActionResult HandleError(int statusCode = 404, Exception exception = null)
        {
            HttpContext.Response.Clear();
            HttpContext.Response.TrySkipIisCustomErrors = true;

            var apiResult = new ApiResult {
                StatusCode = statusCode, Message = HttpWorkerRequest.GetStatusDescription(statusCode)
            };
            var shouldLogout = statusCode == 403;

            if (exception is AggregateException aggregateException)
            {
                aggregateException = aggregateException.Flatten();
                if (aggregateException.InnerExceptions.Count == 1)
                {
                    exception = aggregateException.InnerExceptions[0];
                }
            }

            if (exception != null)
            {
                switch (exception)
                {
                case ArgumentException argumentException:
                    apiResult.StatusCode = 400;
                    apiResult.Message    = argumentException.Message;
                    break;

                case BusinessLogicException businessLogicException:
                    apiResult.Message = businessLogicException.Description;
                    break;

                case NotFoundException notFoundException:
                    apiResult.StatusCode = 404;
                    apiResult.Message    = notFoundException.Description;
                    break;

                default:
                    if (apiResult.StatusCode != 500)
                    {
                        apiResult.Message = exception.Message;
                    }
                    break;
                }
            }

            HttpContext.Response.StatusCode  = apiResult.StatusCode;
            HttpContext.Response.ContentType = "text/html";

            return(new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = apiResult
            });
        }
示例#27
0
        public override void SendKnownResponseHeader(int index, string value)
        {
            if (this._headersSent)
            {
                return;
            }
            switch (index)
            {
            case 1:
            case 2:
            {
                break;
            }

            default:
            {
                switch (index)
                {
                case 18:
                case 19:
                {
                    if (this._specialCaseStaticFileHeaders)
                    {
                        return;
                    }
                    break;
                }

                case 20:
                {
                    if (value == "bytes")
                    {
                        this._specialCaseStaticFileHeaders = true;
                        return;
                    }
                    break;
                }

                default:
                {
                    if (index == 26)
                    {
                        return;
                    }
                    break;
                }
                }
                this._responseHeadersBuilder.Append(HttpWorkerRequest.GetKnownResponseHeaderName(index));
                this._responseHeadersBuilder.Append(": ");
                this._responseHeadersBuilder.Append(value);
                this._responseHeadersBuilder.Append("\r\n");
                return;
            }
            }
        }
示例#28
0
        public override void SendKnownResponseHeader(int index, string value)
        {
            if (HeadersSent())
            {
                return;
            }

            string headerName = HttpWorkerRequest.GetKnownResponseHeaderName(index);

            SendUnknownResponseHeader(headerName, value);
        }
示例#29
0
        private void RaiseEvent(Action <Guid> action, HttpContext context)
        {
            HttpWorkerRequest workerRequest = GetWorkerRequest(context);

            if (workerRequest == null)
            {
                return;
            }

            action(workerRequest.RequestTraceIdentifier);
        }
示例#30
0
        /// <summary>
        /// Gets the message.
        /// </summary>
        /// <param name="statusCode">The status code.</param>
        /// <param name="message">The message.</param>
        /// <returns>The message and the status description.</returns>
        private static string GetMessage(HttpStatusCode statusCode, string message)
        {
            string format = "%s";

            if (!String.IsNullOrWhiteSpace(message))
            {
                format = message;
            }

            return(format.Replace("%s", HttpWorkerRequest.GetStatusDescription((int)statusCode)));
        }
示例#31
0
        private IAsyncResult GenerateErrorResponse(HttpContext context, string message, object extraData)
        {
            context.Response.ClearHeaders();
            context.Response.ClearContent();
            context.Response.Clear();
            context.Response.StatusCode        = (int)HttpStatusCode.MethodNotAllowed;
            context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)HttpStatusCode.MethodNotAllowed);
            context.Response.Write(message);

            return(new AsmxHandlerSyncResult(extraData));
        }
	public HttpContext(HttpWorkerRequest wr) {}
	// Methods
	public static void ProcessRequest(HttpWorkerRequest wr) {}
 public AspNetWebSocketContextImpl(HttpContextBase httpContext = null, HttpWorkerRequest workerRequest = null, AspNetWebSocket webSocket = null) {
     _httpContext = httpContext;
     _workerRequest = workerRequest;
     _webSocket = webSocket;
 }