C# 如何检查HttpPostedFileBase是否为空?

C# 如何检查HttpPostedFileBase是否为空?,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,My ViewModel包含以下两个属性: [DataType(DataType.Upload)] public HttpPostedFileBase ImageFile { get; set; } [DataType(DataType.Upload)] public HttpPostedFileBase AttachmentFile { get; set; } 我的观点是这样写的: @using (Html.BeginForm(null, null, FormMethod.Post, ne

My ViewModel包含以下两个属性:

[DataType(DataType.Upload)]
public HttpPostedFileBase ImageFile { get; set; }
[DataType(DataType.Upload)]
public  HttpPostedFileBase AttachmentFile { get; set; }
我的观点是这样写的:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "product-master-form", enctype = "multipart/form-data" }))
{
  //some html and razor is written here. 
  <div id="attachments" class="tab-pane fade">
   @Html.TextBoxFor(model => model.AttachmentFile, new { type = "file" })
 </div><!--/close attachements pane-->
 <div id="product-image-up" class="tab-pane fade">
   @Html.TextBoxFor(model => model.ImageFile, new { type = "file" })
 </div><!--/close panel for image upload-->
}
if(masterViewModel.ImageFile.ContentLength != 0)
{

 if(masterViewModel.ImageFile.ContentLength > imageSizeLimit)
 {
   otherErrorMessages.Add("Image size cannote be more than " + readableImageSizeLimit);
 }
 if (!validImageTypes.Contains(masterViewModel.ImageFile.ContentType))
 {
   otherErrorMessages.Add("Please choose either a GIF, JPG or PNG image.");
 }
 try
 {
   //code to save file in hard disk is written here. 
 }catch(Exception ex)
 {
  otherErrorMessages.Add("Cannot upload image file: "+ ex);
 }


}//end block for handling images. 
我的问题是在控制器中,如何检查图像文件是否为空?当我提交表单时,图像文件不是表单内部必须填写的字段。当我提交没有图像文件的表单时,代码执行到达以下行:ifmasterViewModel.ImageFile.ContentLength!=0

它将抛出一个异常,声明:对象引用未设置为对象的实例。但是,如果我提交带有图像文件的表单,程序将继续正常执行


先谢谢你

为什么不使用空条件运算符

if(masterViewModel?.ImageFile?.ContentLength != 0)
这样,如果masterViewModel、ImageFile或ContentLength为null,它将短路并返回null。然后null不等于0,因此它将返回false

否则你可以写:

if (masterViewModel != null && masterViewModel.ImageFile != null && masterViewModel.ImageFile.ContentLength != 0)

显然,您要检查masterViewModel.ImageFile==null?这不相关,但您可能还想查看如何使用验证属性对文件类型和大小进行客户端和服务器端验证