如何在Web应用程序中显示错误消息框asp.net c#

我有一个ASP.NET Web应用程序,我想知道如何在抛出exception时显示错误消息框。

例如,

try { do something } catch { messagebox.write("error"); //[This isn't the correct syntax, just what I want to achieve] } 

[消息框显示错误]

谢谢

您无法在客户端的计算机或服务器上合理地显示消息框。 对于客户端的计算机,您将需要重定向到包含相应错误消息的错误页面,如果需要,可能包括exception消息和堆栈跟踪。 在服务器上,您可能希望对事件日志或日志文件进行一些日志记录。

  try { .... } catch (Exception ex) { this.Session["exceptionMessage"] = ex.Message; Response.Redirect( "ErrorDisplay.aspx" ); log.Write( ex.Message + ex.StackTrace ); } 

请注意,上面的“日志”必须由您实现,可能使用log4net或其他一些日志记录实用程序。

您不能只调用messagebox.write,因为您与客户端断开连接。 您应该注册显示消息框的javascript代码:

 this.RegisterClientScriptBlock(typeof(string), "key", string.Format("alert('{0}');", ex.Message), true); 

使用MessageBox.Show()将导致在服务器中显示一个消息框,并阻止线程处理进一步的请求,除非该框已关闭。

你能做的是,

 this.Page.ClientScript.RegisterStartupScript(this.GetType(),"ex","alert('" + ex.Message + "');", true); 

这将在客户端显示exception,前提是exception未冒泡。

我过去这样做的方法是在抛出exception时在页面上填充一些信息。 MessageBox适用于Windows窗体,不能用于Web窗体。 我想你可以在页面上放一些javascript来做警报:

 Response.Write(""); 

我不认为你会想要显示exception的细节。 我们不得不停止这样做,因为我们的一个客户不希望他们的用户看到exception细节中可用的所有内容。 尝试显示一个javascript窗口,其中包含一些信息,说明存在问题。

如果要在单个位置处理所有错误,可以使用web应用程序的global.asax文件(也称为全局应用程序文件),并使用应用程序错误事件。 就像这样,你将全局应用程序文件添加到项目中,然后在Application_Error事件中放入一些error handling代码,如下所示:

  void Application_Error(object sender, EventArgs e) { Exception objErr = Server.GetLastError().GetBaseException(); string err = "Error Caught in Application_Error event\n" + "Error in: " + Request.Url.ToString() + "\nError Message:" + objErr.Message.ToString() + "\nStack Trace:" + objErr.StackTrace.ToString(); System.Diagnostics.EventLog.WriteEntry("Sample_WebApp", err, System.Diagnostics.EventLogEntryType.Error); Server.ClearError(); Response.Redirect(string.Format("{0}?exceptionMessage={1}", System.Web.VirtualPathUtility.ToAbsolute("~/ErrorPage.aspx"), objErr.Message)); } 

这会将您的exception的技术细节记录到系统事件日志中(如果您需要稍后检查错误)然后在您的ErrorPage.aspx上从Page_Load事件的查询字符串捕获exception消息。 如何显示它取决于你(你可以使用其他答案上建议的javascript警告或简单地将文本传递给asp.net文字

希望他的帮助。 干杯

如果您使用带有MVC和Razor的.NET Core,则在呈现页面之前,您需要进行多级预处理。 然后我建议您尝试在视图页面的顶部包装条件错误消息,如下所示:

在ViewController.cs中:

 if (file.Length < 800000) { ViewData["errors"] = ""; } else { ViewData["errors"] = "File too big. (" + file.Length.ToString() + " bytes)"; } 

在View.cshtml中:

 @if (ViewData["errors"].Equals("")) { @:

Everything is fine.

} else { @: }