Umbraco 7 如果文件上传为空

Umbraco 7 if File Upload is empty

我正在使用 Umbraco 7 进行文件上传。我想检查是否有文件上传。

如果没有上传文件,我会收到以下错误:Object reference not set to an instance of an object.

我删除了一些代码以使其更易于阅读,但下面是我的表面控制器:

using System.Web.Mvc;
using Umbraco.Web.Mvc;
using Umbraco.Web;

namespace Sp34k.Controllers
{
    public class GalleryItem
    {
        public string projectFile { get; set; }
    }

    public class PortfolioSurfaceController : SurfaceController
    {
        // GET: PortfolioSurface
        public ActionResult GetCategoryDetails(int id)
        {
            GalleryItem gItem = new GalleryItem();
            var node = Umbraco.TypedContent(id);

            string file = node["uploadProjectFiles"].ToString();

            if (string.IsNullOrWhiteSpace(file))
            {
                gItem.projectFile = node["uploadProjectFiles"].ToString();
            }

            return Json(gItem, JsonRequestBehavior.AllowGet);
        }
    }
}

我认为问题出在这一行:

string file = node["uploadProjectFiles"].ToString();

您可能会从 node 使用该密钥收到 null 作为对此的响应,并且您无法在其上调用 ToString()

还有另一个问题:如果字符串 空值或空格,您将其分配给 gItem.projectFile。我假设您只想在 not null 或 whitespace 时分配它。

如果node中的对象肯定是string或null,可以轻松修改代码:

string file = node["uploadProjectFiles"] as string;

if (!string.IsNullOrWhiteSpace(file))
{
    gItem.projectFile = file;
}

as string 表示 "if the object is a string assign it as such, or if it isn't return null." 这样你要么得到一个字符串(可能仍然是 empty/whitespace),要么得到一个类型为字符串的 null ,你可以检查它。

您正在访问的节点键可能是空的,您也需要检查它是否为空:

string file = node["uploadProjectFiles"] !=null ? node["uploadProjectFiles"].ToString() : String.Empty;

然后接下来使用文件变量:

if (string.IsNullOrWhiteSpace(file))
{
   gItem.projectFile = file;
}