【发布时间】:2015-05-03 20:08:17
【问题描述】:
我有一个控制器 post 方法,需要上传文件:
查看:
@using (Html.BeginForm("UploadCSV", "TemporaryPerson", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
<br />
<input type="file" name="personFile" /><input type="submit" value="Upload" />
</div>
}
和控制器方法:
[HttpPost]
public ActionResult UploadCSV(UploadCsvViewModel model)
{
if (ModelState.IsValid)
{
using (StreamReader reader = new StreamReader(Request.Files[0].InputStream))
{
using (var csv = new CsvReader(reader))
{
var records = csv.GetRecords<TemporaryPersonCsv>().ToList();
foreach (var record in records)
{
//...................
}
}
}
}
return View();
}
它工作正常。但我想将所有验证移至 UploadCsvViewModel:
public class UploadCsvViewModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (HttpContext.Current.Request.Files == null || HttpContext.Current.Request.Files.Count == 0 || HttpContext.Current.Request.Files[0].ContentLength == 0)
results.Add(new ValidationResult("File is not selected or empty", new string[] { "NoFile" }));
using (StreamReader reader = new StreamReader(HttpContext.Current.Request.Files[0].InputStream))
{
using (var csv = new CsvReader(reader))
{
var enumeraterecords = csv.GetRecords<TemporaryPersonCsv>();
if (enumeraterecords != null)
{
var records = enumeraterecords.ToList();
if (records == null || records.Count == 0)
results.Add(new ValidationResult("No records in file", new string[] { "NoRecords" }));
// different validation, according with business logic
}
else
results.Add(new ValidationResult("No records in file", new string[] { "NoRecords" }));
}
}
return results;
}
}
问题是如果我在 UploadCsvViewModel 中有 Validate 方法,则会出现错误:
异常详细信息:CsvHelper.CsvReaderException:没有标头记录 找到了。
上线:
var records = csv.GetRecords<TemporaryPersonCsv>().ToList();
在控制器方法中。我假设 InputStream 的位置无效。我试过了:
-
复制到另一个流:
using (MemoryStream ms = new MemoryStream()) { HttpContext.Current.Request.Files[0].InputStream.CopyTo(ms, HttpContext.Current.Request.Files[0].ContentLength);
没有帮助
-
在 validate 方法结束时将输入流位置设置为 0:
HttpContext.Current.Request.Files[0].InputStream.Position = 0;
没有帮助
-
为“阅读器”对象调用 DiscardBufferedData
reader.DiscardBufferedData();
也没有帮助。
【问题讨论】:
-
你真的想读两次文件,只是为了验证它的内容吗?
-
在模型类的 Validate 方法中验证数据的任何其他方法?
标签: c# validation stream asp.net-mvc-5 inputstream