gpt4 book ai didi

c# - 如何捕获违反 maxRequestLength 的 ConfigurationErrorsException?

转载 作者:可可西里 更新时间:2023-11-01 09:12:15 25 4
gpt4 key购买 nike

我正在限制用户可以从 Web.config 上传到站点的文件大小。正如解释的那样 here ,如果不接受大小,它应该抛出 ConfigurationErrorsException。我试图从上传请求的操作方法或 Controller 中捕获它,但没有成功。连接已重置,我无法让它显示错误页面。

我尝试在 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");
}
}

但我还是明白了:

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.

更新:

到底是什么方法引发了异常?如果我阅读请求,它会引发异常如果我根本不阅读它,我会在浏览器中看到“101 连接重置”。这里可以做什么?

最佳答案

你不能在 action 方法中捕获错误,因为异常来得更早,但你可以在这里捕获它

protected void Application_Error() {
var lastError = Server.GetLastError();
if(lastError !=null && lastError is HttpException && lastError.Message.Contains("exceed")) {
Response.Redirect("~/errors/RequestLengthExceeded");
}
}

实际上当文件大小超过限制时会出现 HttpException 错误。

IIS 对内容也有限制——无法在应用程序中捕获。 IIS 7 抛出

HTTP Error 404.13 - Not Found The request filtering module is configured to deny a request that exceeds the request content length.

你可以google一下,关于这个iis错误的信息很多。

关于c# - 如何捕获违反 maxRequestLength 的 ConfigurationErrorsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2756448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com