c#异步文件扩展名检查操作过滤器ActionFilterAttribute

时间:2017-06-07 11:53:20

标签: c# actionfilterattribute

背后的想法是我有一个正在检查文件扩展名的ActionFilterAttribute。如果存在文件扩展名,则可以传递否则抛出错误。我在不同的地方有多个文件上载。

我有一个单页面应用程序在运行,用户可以上传文件。它运行在javascript knockout.js和c#。

问题是我在MultipartMemoryStreamProvider

中总是得到Count = 0

以下是在第一行调用ActionFilterAttribute的代码

[DocumentUploadValidationAttribute]
    [HttpPost, Route("documents/upload/{customerId}/{documentType}")]
    public async Task<IHttpActionResult> UploadCustomerDocument(int customerId, string documentType)
    {
        try
        {
            await data.Document.UploadCustomerDocument(Request, customerId, documentType);
            return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

ActionFilterAttribute看起来像这样。在foreach循环provider.Content是0,但为什么?

namespace VZ.VMS.UI.Validation {
public class DocumentUploadValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var provider = new MultipartMemoryStreamProvider();
        var task = actionContext.Request.Content.ReadAsMultipartAsync(provider);

        foreach (var file in provider.Contents)
        {
            var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            var extension = Path.GetExtension(filename).Replace(".", "");

            if (extension != "pdf" && extension != "docx" && extension != "xlsx" && extension != "img" && extension != "png")
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, new { errorMessage = "error_code" }, actionContext.ControllerContext.Configuration.Formatters.JsonFormatter);
            }
        }

        base.OnActionExecuting(actionContext);
    }
}
}

0 个答案:

没有答案