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

时间:2022-11-09 03:35:41

I have an ASP.NET web application, and I wanted to know how I could display an error message box when an exception is thrown.

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

For example,

例如,

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

[The message box shows the error]

[消息框显示错误]

Thank you

谢谢

7 个解决方案

#1


12  

You can't reasonably display a message box either on the client's computer or the server. For the client's computer, you'll want to redirect to an error page with an appropriate error message, perhaps including the exception message and stack trace if you want. On the server, you'll probably want to do some logging, either to the event log or to a log file.

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

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

Note that the "log" above would have to be implemented by you, perhaps using log4net or some other logging utility.

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

#2


12  

You cannot just call messagebox.write cause you are disconnected from the client. You should register javascript code that shows a messagebox:

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

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

#3


5  

using MessageBox.Show() would cause a message box to show in the server and stop the thread from processing further request unless the box is closed.

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

What you can do is,

你能做的是,

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

this would show the exception in client side, provided the exception is not bubbled.

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

#4


2  

The way I've done this in the past is to populate something on the page with information when an exception is thrown. MessageBox is for windows forms and cannot be used for web forms. I suppose you could put some javascript on the page to do an alert:

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

Response.Write("<script>alert('Exception: ')</script>");

#5


1  

I wouldn't think that you would want to show the details of the exception. We had to stop doing this because one of our clients didn't want their users seeing everything that was available in the exception detail. Try displaying a javascript window with some information in it explaining that there has been a problem.

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

#6


1  

If you want to handle all your error on a single place, you can use the global.asax file (also known as global application file) of your webapplication, and work with the application error event. It goes like this Firts you add the global application file to your project, then on the Application_Error event you put some error handling code, like this:

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

    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));
}

This will log the technical details of your exception into the system event log (if you need to check the error later) Then on your ErrorPage.aspx you capture the exception message from the querystring on the Page_Load event. How to display it is up to you (you can use the javascript alert suggested on the other answers or simple pass the text to a asp.net literal

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

Hope his helps. Cheers

希望他的帮助。干杯

#7


1  

If you are using .NET Core with MVC and Razor, you have several levels of preprocessing before your page is rendered. Then I suggest that you try wrapping a conditional error message at the top of your view page, like so:

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

In ViewController.cs:

在ViewController.cs中:

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

In View.cshtml:

在View.cshtml中:

@if (ViewData["errors"].Equals(""))
{
    @:<p>Everything is fine.</p>
}
else
{
    @:<script>alert('@ViewData["errors"]');</script>
}

#1


12  

You can't reasonably display a message box either on the client's computer or the server. For the client's computer, you'll want to redirect to an error page with an appropriate error message, perhaps including the exception message and stack trace if you want. On the server, you'll probably want to do some logging, either to the event log or to a log file.

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

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

Note that the "log" above would have to be implemented by you, perhaps using log4net or some other logging utility.

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

#2


12  

You cannot just call messagebox.write cause you are disconnected from the client. You should register javascript code that shows a messagebox:

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

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

#3


5  

using MessageBox.Show() would cause a message box to show in the server and stop the thread from processing further request unless the box is closed.

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

What you can do is,

你能做的是,

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

this would show the exception in client side, provided the exception is not bubbled.

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

#4


2  

The way I've done this in the past is to populate something on the page with information when an exception is thrown. MessageBox is for windows forms and cannot be used for web forms. I suppose you could put some javascript on the page to do an alert:

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

Response.Write("<script>alert('Exception: ')</script>");

#5


1  

I wouldn't think that you would want to show the details of the exception. We had to stop doing this because one of our clients didn't want their users seeing everything that was available in the exception detail. Try displaying a javascript window with some information in it explaining that there has been a problem.

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

#6


1  

If you want to handle all your error on a single place, you can use the global.asax file (also known as global application file) of your webapplication, and work with the application error event. It goes like this Firts you add the global application file to your project, then on the Application_Error event you put some error handling code, like this:

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

    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));
}

This will log the technical details of your exception into the system event log (if you need to check the error later) Then on your ErrorPage.aspx you capture the exception message from the querystring on the Page_Load event. How to display it is up to you (you can use the javascript alert suggested on the other answers or simple pass the text to a asp.net literal

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

Hope his helps. Cheers

希望他的帮助。干杯

#7


1  

If you are using .NET Core with MVC and Razor, you have several levels of preprocessing before your page is rendered. Then I suggest that you try wrapping a conditional error message at the top of your view page, like so:

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

In ViewController.cs:

在ViewController.cs中:

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

In View.cshtml:

在View.cshtml中:

@if (ViewData["errors"].Equals(""))
{
    @:<p>Everything is fine.</p>
}
else
{
    @:<script>alert('@ViewData["errors"]');</script>
}