当前位置: 首页>>代码示例>>C#>>正文


C# HttpContext.AddError方法代码示例

本文整理汇总了C#中System.Web.HttpContext.AddError方法的典型用法代码示例。如果您正苦于以下问题:C# HttpContext.AddError方法的具体用法?C# HttpContext.AddError怎么用?C# HttpContext.AddError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Web.HttpContext的用法示例。


在下文中一共展示了HttpContext.AddError方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: EncodeError_FromHttpContext

        public void EncodeError_FromHttpContext()
        {
            // setup
            const string url = "http://myserver.com/site/page?param=value";
            var x = new HttpContext(new HttpRequest("file", url, "param=value"), new HttpResponse(TextWriter.Null));
            var guid = Guid.NewGuid();
            x.Items.Add("loggingId", guid);
            const string msg = "booboo";
            Exception exc;
            try
            {
                throw new Exception(msg); // to get a stack trace
            }
            catch (Exception ex)
            {
                exc = ex;
            }
            x.AddError(exc);

            // test
            var res = ServerErrorHttpModule.EncodeError(x);

            // sense
            var dec = Encoding.UTF8.GetString(Convert.FromBase64String(res));
            Assert.False(string.IsNullOrEmpty(dec));
            var parts = dec.Split(ServerErrorHttpModule.ErrorSepChar);
            Assert.Equal(4, parts.Length);
            Assert.True(parts.Contains(guid.ToString()));
            Assert.True(parts.Contains(url));
            Assert.True(parts.Contains(msg));
            Assert.Equal(1, parts.Count(p => p.Contains("EncodeError_FromHttpContext")));
        }
开发者ID:grbbod,项目名称:drconnect-jungo,代码行数:32,代码来源:ServerErrorHttpModuleTests.cs

示例2: BeginProcessRequest

        protected override IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)
        {
            string pais = ObterCodigoPais(httpContext.Request.UserHostAddress);

            if (this.paises.Contains(pais))
                httpContext.AddError(new Exception("Desculpe! Você não pode acessar esta página a partir do seu país."));

            return base.BeginProcessRequest(httpContext, callback, state);
        }
开发者ID:rkiguti,项目名称:CustomRoute,代码行数:9,代码来源:BloqueioIpHandler.cs

示例3: ProcessRequest

        //***************************************************************************
        // Public Methods
        // 
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;

            string
                reqImg = req["imgNm"];

            try
            {
                object objImg = null;
                try
                {
                    if (!string.IsNullOrEmpty(reqImg))
                        objImg = global::RainstormStudios.Web.Properties.Resources.ResourceManager.GetObject(reqImg);

                    if (!string.IsNullOrEmpty(reqImg) && objImg == null)
                        context.AddError(new Exception("Unable to find requested image name.  Returning generic folder image."));

                    if (objImg == null)
                        objImg = global::RainstormStudios.Web.Properties.Resources.ResourceManager.GetObject("folder");

                    if (objImg == null)
                        throw new Exception("Unable to find any image resources.");

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ((Bitmap)objImg).Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                        context.Response.StatusCode = 200;
                        context.Response.ContentType = "image/gif";
                        byte[] imgBts = ms.ToArray();
                        context.Response.OutputStream.Write(imgBts, 0, imgBts.Length);
                    }
                }
                finally
                {
                    if (objImg != null && objImg is IDisposable)
                        ((IDisposable)objImg).Dispose();
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
            }
        }
开发者ID:tenshino,项目名称:RainstormStudios,代码行数:47,代码来源:DirectoryListTreeViewImageHandler.cs

示例4: RunContext

        public static Task RunContext(HttpContext context)
        {
            if (_app == null)
            {
                Initialize(context);
                if (_app == null)
                {
                    throw new InvalidOperationException("No application found.");
                }
            }

            var env = CreateEnvironmentHash(context);
            var tcs = new TaskCompletionSource<object>();
            env.Add(OwinKeys.CallCompleted, tcs.Task);
            var task = _app(env);
            return task
                .ContinueWith(t =>
                                  {
                                      if (t.Exception != null)
                                      {
                                          context.Response.StatusCode = 500;

                                          foreach (Exception ex in t.Exception.InnerExceptions)
                                          {
                                              context.AddError(ex);
                                          }
                                      }
                                      else if (!env.ContainsKey(OwinKeys.ResponseStatusCode))
                                      {
                                          context.Response.StatusCode = 404;
                                      }
                                      else
                                      {
                                          context.Response.StatusCode = (int)env[OwinKeys.ResponseStatusCode];
                                      }

                                      if (env.ContainsKey(OwinKeys.ResponseHeaders))
                                      {
                                          WriteHeaders((IDictionary<string, string[]>)env[OwinKeys.ResponseHeaders], context);
                                      }
                                      return TaskHelper.Completed();

                                  }, TaskContinuationOptions.None)
                .Unwrap()
                .ContinueWith(t => SetOwinCallCompleted(t, tcs));
        }
开发者ID:EddieGarmon,项目名称:Fix,代码行数:46,代码来源:Bridge.cs

示例5: ArgumentNullException

		void IHttpHandler.ProcessRequest(HttpContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");

			Context = context;

			try
			{
				JsonHandler.JsonResponse(context.Response, new Action<JsonWriter>(WriteResult));
			}
			catch (Exception exception)
			{
				context.AddError(exception);
				OnError(EventArgs.Empty);
				if (context.Error != null)
				{
					throw new HttpUnhandledException("blah", exception);
				}
			}
		}
开发者ID:edwardt,项目名称:MySpace-Data-Relay,代码行数:21,代码来源:JsonHandler.cs

示例6: ProcessRequest

        //***************************************************************************
        // Public Methods
        // 
        public void ProcessRequest(HttpContext context)
        {
            Exception exKeep = null;
            string
                strW = context.Request.Params["w"],
                strH = context.Request.Params["h"],
                strFgClr = context.Request.Params["fg"],
                strBgClr = context.Request.Params["bg"],
                strFont = context.Request.Params["fnt"],
                strSize = context.Request.Params["sz"],
                strStyle = context.Request.Params["st"],
                strFormat = context.Request.Params["fmt"],
                strAlign = context.Request.Params["aln"];

            int iW = 0,
                iH = 0;
            Color
                fgClr = Color.Empty,
                bgClr = Color.Empty,
                tdClr = Color.Empty;
            float
                fSZ = 0.9f;
            int iFgClr = 0,
                iBgClr = 0,
                iTdClr = 0;
            FontStyle
                style = FontStyle.Regular;
            int iFntStyle = 0;
            System.Web.UI.WebControls.HorizontalAlign
                align = System.Web.UI.WebControls.HorizontalAlign.NotSet;

            try
            {
                if (!int.TryParse(strW, out iW))
                    context.AddError(new ArgumentException("Specified 'Width' is not a valid integer value."));
                if (!int.TryParse(strH, out iH))
                    context.AddError(new ArgumentException("Specified 'Height' is not a valid integer value."));

                if (string.IsNullOrEmpty(strFormat))
                    strFormat = "hh:MM:ss tt";

                if (!string.IsNullOrEmpty(strFgClr))
                    if (int.TryParse(strFgClr, out iFgClr))
                        fgClr = Color.FromArgb(iFgClr);
                    else
                        fgClr = Color.FromName(strFgClr);
                else
                    fgClr = Color.Black;
                if (fgClr == null || fgClr == Color.Empty)
                    context.AddError(new ArgumentException("Specified foreground color could not be parsed."));

                if (!string.IsNullOrEmpty(strBgClr))
                    if (int.TryParse(strBgClr, out iBgClr))
                        bgClr = Color.FromArgb(iBgClr);
                    else
                        bgClr = Color.FromName(strBgClr);
                else
                    bgClr = Color.White;
                if (bgClr == null || bgClr == Color.Empty)
                    context.AddError(new ArgumentException("Specified background color could not be parsed."));

                if (!float.TryParse(strSize, out fSZ))
                    context.AddError(new ArgumentException("Specified font size is not a valid floating point integer value."));

                // Try and parse the font style value into an integer as a check to
                //   see what kind of value was passed.
                if (int.TryParse(strStyle, out iFntStyle))
                    // If the value is an integer, it's probably a bit array of
                    //   enumeration flags.
                    style = (FontStyle)iFntStyle;
                else
                    // If the value is not an integer, try and parse the enumeration
                    //   value directly.
                    style = (string.IsNullOrEmpty(strStyle))
                        ? FontStyle.Regular
                        : (FontStyle)Enum.Parse(typeof(FontStyle), strStyle, true);

                align = (string.IsNullOrEmpty(strAlign))
                        ? System.Web.UI.WebControls.HorizontalAlign.NotSet
                        : (System.Web.UI.WebControls.HorizontalAlign)Enum.Parse(typeof(System.Web.UI.WebControls.HorizontalAlign), strAlign);
            }
            catch (Exception ex)
            {
                exKeep = ex;
            }

            using (Bitmap bmp = new Bitmap(iW, iH))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    if (exKeep == null)
                    {
                        g.Clear(bgClr);
                        using (StringFormat format = new StringFormat(StringFormatFlags.NoWrap))
                        {
                            if (align == System.Web.UI.WebControls.HorizontalAlign.Center)
                                format.Alignment = StringAlignment.Center;
//.........这里部分代码省略.........
开发者ID:tenshino,项目名称:RainstormStudios,代码行数:101,代码来源:Clock.cs

示例7: FinishRequestNotification

 private void FinishRequestNotification(IIS7WorkerRequest wr, HttpContext context, ref RequestNotificationStatus status)
 {
   HttpApplication applicationInstance = context.ApplicationInstance;
   if (context.NotificationContext.RequestCompleted)
     status = RequestNotificationStatus.FinishRequest;
   context.ReportRuntimeErrorIfExists(ref status);
   if (status == RequestNotificationStatus.FinishRequest && (context.CurrentNotification == RequestNotification.LogRequest || context.CurrentNotification == RequestNotification.EndRequest))
     status = RequestNotificationStatus.Continue;
   IntPtr requestContext = wr.RequestContext;
   bool sendHeaders = UnsafeIISMethods.MgdIsLastNotification(requestContext, status);
   try
   {
     context.Response.UpdateNativeResponse(sendHeaders);
   }
   catch (Exception ex)
   {
     wr.UnlockCachedResponseBytes();
     context.AddError(ex);
     context.ReportRuntimeErrorIfExists(ref status);
     context.Response.UpdateNativeResponse(sendHeaders);
   }
   if (sendHeaders)
     context.FinishPipelineRequest();
   if (status == RequestNotificationStatus.Pending)
     return;
   PipelineRuntime.DisposeHandler(context, requestContext, status);
 }
开发者ID:consumentor,项目名称:Server,代码行数:27,代码来源:HttpRuntime.cs

示例8: ProcessRequestNotificationPrivate

 private RequestNotificationStatus ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
 {
   RequestNotificationStatus status = RequestNotificationStatus.Pending;
   try
   {
     int currentModuleIndex;
     bool isPostNotification;
     int currentNotification;
     UnsafeIISMethods.MgdGetCurrentNotificationInfo(wr.RequestContext, out currentModuleIndex, out isPostNotification, out currentNotification);
     context.CurrentModuleIndex = currentModuleIndex;
     context.IsPostNotification = isPostNotification;
     context.CurrentNotification = (RequestNotification) currentNotification;
     IHttpHandler httpHandler = (IHttpHandler) null;
     if (context.NeedToInitializeApp())
     {
       try
       {
         this.EnsureFirstRequestInit(context);
       }
       catch
       {
         if (!context.Request.IsDebuggingRequest)
           throw;
       }
       context.Response.InitResponseWriter();
       httpHandler = HttpApplicationFactory.GetApplicationInstance(context);
       if (httpHandler == null)
         throw new HttpException(System.Web.SR.GetString("Unable_create_app_object"));
       if (EtwTrace.IsTraceEnabled(5, 1))
         EtwTrace.Trace(EtwTraceType.ETW_TYPE_START_HANDLER, context.WorkerRequest, httpHandler.GetType().FullName, "Start");
       HttpApplication httpApplication = httpHandler as HttpApplication;
       if (httpApplication != null)
         httpApplication.AssignContext(context);
     }
     wr.SynchronizeVariables(context);
     if (context.ApplicationInstance != null)
     {
       if (context.ApplicationInstance.BeginProcessRequestNotification(context, this._requestNotificationCompletionCallback).CompletedSynchronously)
         status = RequestNotificationStatus.Continue;
     }
     else if (httpHandler != null)
     {
       httpHandler.ProcessRequest(context);
       status = RequestNotificationStatus.FinishRequest;
     }
     else
       status = RequestNotificationStatus.Continue;
   }
   catch (Exception ex)
   {
     status = RequestNotificationStatus.FinishRequest;
     context.Response.InitResponseWriter();
     context.AddError(ex);
   }
   if (status != RequestNotificationStatus.Pending)
     this.FinishRequestNotification(wr, context, ref status);
   return status;
 }
开发者ID:consumentor,项目名称:Server,代码行数:58,代码来源:HttpRuntime.cs

示例9: WriteExceptionJsonString

        internal static void WriteExceptionJsonString(HttpContext context, Exception ex, JavaScriptSerializer serializer)
        {
            context.Response.ClearHeaders();
            context.Response.ClearContent();
            context.Response.Clear();
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)HttpStatusCode.InternalServerError);
            context.Response.ContentType = "application/json";
            context.Response.AddHeader("jsonerror", "true");
            using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, new UTF8Encoding(false)))
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                context.AddError(ex);

                if (context.IsCustomErrorEnabled)
                {
                    writer.Write(serializer.Serialize(new WebServiceError("Error occured while processing request", String.Empty, String.Empty)));
                }
                else
                {
                    writer.Write(serializer.Serialize(new WebServiceError(ex.Message, ex.StackTrace, ex.GetType().FullName)));
                }
                writer.Flush();
            }
        }
开发者ID:modulexcite,项目名称:dropthings,代码行数:29,代码来源:WebServiceHelper.cs

示例10: ProcessRequest

        //***************************************************************************
        // Public Methods
        // 
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;

            string
                strImgPath = req["imgpth"],
                strExt = req["ext"];

            try
            {
                if (!string.IsNullOrEmpty(strImgPath))
                {
                    // If the application provided an alternate image file path, look
                    //   there first.
                    string lcPath = System.IO.Path.Combine(context.Server.MapPath(strImgPath), strExt + ".gif");
                    if (System.IO.File.Exists(lcPath))
                        context.Response.WriteFile(lcPath);
                    return;
                }

                object objImg = null;
                try
                {
                    // If we didn't find the icon in the alternate image path, then
                    //   check the local resources.
                    objImg = global::RainstormStudios.Web.HttpHandlers.Properties.Resources.ResourceManager.GetObject(strExt);

                    if (objImg == null)
                    {
                        // If we didn't found it with any method above, just pull the
                        //   'generic' file icon from the resource collection.
                        objImg = global::RainstormStudios.Web.HttpHandlers.Properties.Resources.ResourceManager.GetObject("file");
                    }

                    if (objImg == null)
                        throw new Exception("Unable to determine any images for file type icon.");

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ((Bitmap)objImg).Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                        context.Response.StatusCode = 200;
                        context.Response.ContentType = "image/gif";
                        byte[] imgBts = ms.ToArray();
                        context.Response.OutputStream.Write(imgBts, 0, imgBts.Length);
                    }

                }
                finally
                {
                    if (objImg != null && objImg is IDisposable)
                        ((IDisposable)objImg).Dispose();
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
            }
        }
开发者ID:tenshino,项目名称:RainstormStudios,代码行数:61,代码来源:FileTypeIcon.cs


注:本文中的System.Web.HttpContext.AddError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。