MVC5使用Controller来提供图像,值不能为空

时间:2015-09-30 19:26:43

标签: asp.net controller asp.net-mvc-5

我是MVC的新手,我跟着另一个关于将本地文件加载到网页的教程,虽然它似乎适用于其他人但是我收到了错误。

public class ImagesController : Controller
{
    // GET: Images
    public ActionResult SomeImage(string imageName)
    {
        var root = @"C:\Images\";
        var path = Path.Combine(root, imageName);
        path = Path.GetFullPath(path);
        if (!path.StartsWith(root))
        {
            // Ensure that we are serving file only inside the root folder
            // and block requests outside like "../web.config"
            throw new HttpException(403, "Forbidden");
        }

        return File(path, "image/png");
    }
}

我得到的错误是:

An exception of type 'System.ArgumentNullException' occurred in mscorlib.dll but was not handled in user code Additional information: Value cannot be null.

它突出显示的是:

var path = Path.Combine(root, imageName);

2 个答案:

答案 0 :(得分:2)

使用shape帮助程序时,匿名对象中的属性名称必须与操作中参数的名称匹配。

在你的情况下:

Url.Action()

答案 1 :(得分:1)

如上所述haim770,您似乎缺少imageName参数的“Name”部分。您当然可以为代码添加错误处理,以便本地化异常。这可能有助于缩小任何编码问题。

if(imageName == null)
{
    throw new ArgumentNullException(null, "imageName is NULL");
}