我试图为我的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将空字符串返回给调用者?
答案 0 :(得分:3)
context.Response
本身来返回ajax响应。只需在那里写下空字符串。HttpApplication.EndRequest
。这就是您实际可以更改(甚至替换)HTTP响应的地方。HttpApplication.PreSendRequestHeaders
事件:您可以将PreSendRequestHeaders和PreSendRequestContext事件与本机IIS模块一起使用,但不要将它们与实现IHttpModule 的托管模块一起使用。设置这些属性可能会导致异步请求出现问题。
来自What not to do in ASP.NET, and what to do instead。
修改强>
也许是这样的?
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();
}
}
}