Ufu*_*arı 10 c# error-handling asp.net-mvc web-config
我限制文件大小用户可以从Web.config上传到站点.正如解释在这里,它应该抛出一个ConfigurationErrorsException如果大小是不能接受的.我试图从动作方法或控制器中捕获上传请求,但没有运气.连接被重置,我无法显示错误页面.
我尝试在BeginRequest事件中捕获它,但无论我做什么,异常都是未处理的.这是代码:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
try
{
if (context.Request.ContentLength > maxRequestLength)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
// Check if body contains data
if (workerRequest.HasEntityBody())
{
// get the total body length
int requestLength = workerRequest.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = 0;
if (workerRequest.GetPreloadedEntityBody() != null)
initialBytes = workerRequest.GetPreloadedEntityBody().Length;
if (!workerRequest.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512];
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
}
}
catch(HttpException)
{
context.Response.Redirect(this.Request.Url.LocalPath + "?action=exception");
}
}
Run Code Online (Sandbox Code Playgroud)
但我仍然得到这个:
Maximum request length exceeded.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Maximum request length exceeded.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Run Code Online (Sandbox Code Playgroud)
更新:
无论如何,什么方法引发了异常?如果我读取请求它引发异常如果我根本不读它,我在浏览器中得到"101连接重置".这可以做什么?
你不能在行动方法中捕获错误因为异常来得更早,但你可以在这里抓住它
protected void Application_Error() {
var lastError = Server.GetLastError();
if(lastError !=null && lastError is HttpException && lastError.Message.Contains("exceed")) {
Response.Redirect("~/errors/RequestLengthExceeded");
}
}
Run Code Online (Sandbox Code Playgroud)
Actualy当文件大小超过限制时会出现HttpException错误.
内容上还有IIS限制 - 无法在应用程序中获取.IIS 7抛出
HTTP错误404.13 - 未找到请求筛选模块配置为拒绝超过请求内容长度的请求.
你可以google它,有很多关于这个iis错误的信息.
如果没有客户端的帮助,就没有办法正确地做到这一点。除非您阅读全部内容,否则您无法确定请求是否太长。如果您读完每个请求,任何人都会过来让您的服务器忙碌。如果你只看内容长度并放弃请求,对方会认为存在连接问题。错误处理对此无能为力,这是 HTTP 的一个缺点。
您可以使用 Flash 或 Javascript 组件来解决这个问题,因为这个东西不能很好地失败。
| 归档时间: |
|
| 查看次数: |
4846 次 |
| 最近记录: |