我正试图为我的MVC应用程序创建一个HttpModule,它将拦截文件上传请求。
目标是在发送请求之前捕获请求,以便检查请求的内容长度。
如果内容长度大于允许的长度,它应该取消该请求并发送一个空字符串作为响应。
当用户单击上传文档时,会对UploadSignedDocument操作进行ajax调用:
[NoCache, HttpPost, ValidateAntiForgeryToken]
public string UploadSignedDocument(int orderid, HttpPostedFileBase fileUpload)
{
try
{
var fileinfo = new FileInfo(fileUpload.FileName);
var newFileName = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss_") + fileinfo.Name;
var docPath = Path.Combine(Server.MapPath("~/Uploads/"), newFileName);
fileUpload.SaveAs(docPath);
return newFileName;
}
catch
{
return "";
}
}
它被以下HttpModule截获:
public class UploadedFileSizeScreeningModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.EndRequest += ValidateUploadRequest;
}
public void Dispose()
{
}
private static void ValidateUploadRequest(object source, EventArgs e)
{
HttpApplication context = source as HttpApplication;
if (context.Request.HttpMethod.ToUpperInvariant() != "POST" ||
!context.Request.Path.Contains("OrderQueue/UploadSignedDocument"))
{
return;
}
var requestLengthInMB = context.Request.ContentLength / 1024 / 1024;
if (requestLengthInMB > Settings.Default.MaxFileSizeInMB)
{
// TODO: Return new response (empty string)
}
}
}
如何从HttpHandler将空字符串返回给调用者?
- 您应该使用
context.Response
本身来返回ajax响应。把空字符串写进去 - 您应该订阅
HttpApplication.EndRequest
。这就是您可能实际更改(甚至替换)HTTP响应的地方 - 您应该而不是使用
HttpApplication.PreSendRequestHeaders
事件:
您可以将PreSendRequestHeaders和PreSendRequestContext事件与本机IIS模块一起使用,但不要将它们与实现IHttpModule的托管模块一起使用。设置这些属性可能会导致异步请求出现问题。
从在ASP.NET中不做什么,以及改为做什么。
编辑
也许是这样的?
public class UploadedFileSizeScreeningModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.EndRequest += ValidateUploadRequest;
}
public void Dispose()
{}
private static void ValidateUploadRequest(object source, EventArgs e)
{
HttpApplication context = source as HttpApplication;
if (context.Request.HttpMethod.ToUpperInvariant() != "POST" ||
!context.Request.Path.Contains("OrderQueue/UploadSignedDocument"))
{
return;
}
var requestLengthInMB = context.Request.ContentLength / 1024 / 1024;
if (requestLengthInMB > Settings.Default.MaxFileSizeInMB)
{
context.Response.Clear();
context.Response.Write(string.Empty);
context.Response.End();
}
}
}