简体   繁体   English

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

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

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

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

You cannot just call messagebox.write cause you are disconnected from the client.您不能只调用 messagebox.write ,因为您已与客户端断开连接。 You should register javascript code that shows a messagebox:您应该注册显示消息框的 javascript 代码:

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

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.如果异常没有冒泡,这将在客户端显示异常。

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. MessageBox 适用于 windows forms,不能用于 web forms I suppose you could put some javascript on the page to do an alert:我想你可以在页面上放一些 javascript 来发出警报:

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

If you are using .NET Core with MVC and Razor, you have several levels of preprocessing before your page is rendered.如果您将 .NET Core 与 MVC 和 Razor 一起使用,则在呈现页面之前有几个级别的预处理。 Then I suggest that you try wrapping a conditional error message at the top of your view page, like so:然后我建议您尝试在视图页面的顶部包装一条条件错误消息,如下所示:

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

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.如果您想在一个地方处理所有错误,您可以使用 web 应用程序的 global.asax 文件(也称为全局应用程序文件),并使用应用程序错误事件。 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:首先您将全局应用程序文件添加到您的项目中,然后在 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.这会将您的异常的技术细节记录到系统事件日志中(如果您需要稍后检查错误)然后在您的 ErrorPage.aspx 上,您从 Page_Load 事件的查询字符串中捕获异常消息。 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如何显示它取决于您(您可以使用其他答案中建议的 javascript 警报或简单地将文本传递给 asp.net 文字

Hope his helps.希望他的帮助。 Cheers干杯

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 window,其中包含一些说明存在问题的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM