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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/651592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:52:30  来源:igfitidea点击:

How to display an error message box in a web application asp.net c#

c#asp.netweb-applicationsmessagebox

提问by zohair

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

谢谢

采纳答案by tvanfosson

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 或其他一些日志实用程序。

回答by Michiel Overeem

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

回答by Perchik

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

回答by Jeremy Cron

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 窗口,其中包含一些说明出现问题的信息。

回答by Ramesh

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.

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

回答by Jaime

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

希望他的帮助。干杯

回答by Ulf Lunde

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:

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

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