我正在尝试为我的 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 返回一个空字符串给调用者?