Catch IIS level error to handle in ASP.NET

自作多情 提交于 2019-12-04 12:31:38

You can get access to the exception when the request length is exceeded. Use an HttpModule, and add a handler for the Error event.

The exception is of type: System.Web.HttpUnhandledException (with an InnerException of type: System.Web.HttpException).

To catch this exception, add this to your web.config:

<httpModules>
    <add name="ErrorHttpModule" type="ErrorHttpModule"/>
</httpModules>

And add this class to your App_Code folder:

public class ErrorHttpModule : IHttpModule
{
    private HttpApplication _context;

    public ErrorHttpModule() {
    }

    private void ErrorHandler(Object sender, EventArgs e)
    {
        Exception ex = _context.Server.GetLastError();

        //You can also call this to clear the error
        //_context.Server.ClearError();
    }

    #region IHttpModule Members

    public void Init(HttpApplication context)
    {
        _context = context;
        _context.Error += new EventHandler(ErrorHandler);
    }

    public void Dispose()
    {
    }

    #endregion
}

If you're using the traditional asp:FileUpload control, then there isn't a way to check the size of the files before. However, you can use a Flash or Silverlight approach. One option that has been suggested to me is Uploadify

I don't know for sure that this will work, but at least in IIS 7 you might try catching the Error event in an HttpModule that's configured to run for static files. From there, you could redirect to an appropriate error page.

You can catch these in Global (the global.asax.cs file). Add an Application_Error handler - you will get an HttpUnhandledException. Its InnerException will be an HttpException with the message "Maximum request length exceeded".

However, these errors are handled before your page code ever gets loaded or executed, so there is no way for your page to catch the exception or to know it ever happened. After catching this exception, you could stick a message in your Session for later display. You could also call response.Redirect from Global to display a new page, or redisplay the original with the error message from Session.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!