【问题标题】:MVC5 Using Controller to serve images, value can not be nullMVC5 使用控制器提供图像,值不能为空
【发布时间】:2015-10-01 03:40:43
【问题描述】:

我是 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);

【问题讨论】:

  • imageName 是否为空?
  • 显然root 不为空。因此imageName 必须为空。你验证过imageName的值是什么吗?
  • imageName 是我在视图中设置的任何内容,因此我目前正在使用:<img class="img-responsive" src="@Url.Action("SomeImage", "Images", new { image = "Logo.png" })" alt="" />
  • 你需要new { imageName = "Logo.png" }
  • @haim770 啊,菜鸟的错误,谢谢。如果您将其创建为答案,我将很乐意接受。

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


【解决方案1】:

使用Url.Action() helper 时,匿名对象中的属性名称必须与操作中的参数名称匹配。

在你的情况下:

@Url.Action("SomeImage", "Images", new { imageName = "Logo.png" })

【讨论】:

    【解决方案2】:

    正如haim770 提到的,您似乎缺少 imageName 参数的“名称”部分。您当然可以在代码中添加错误处理以本地化异常。这可能会帮助您缩小任何编码问题的范围。

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

    【讨论】:

    • 我会使用方法 String.IsNullOrEmpty :)
    • 好点。我一直在使用它,但我没有写它。我的错!
    猜你喜欢
    • 2020-09-25
    • 2021-03-28
    • 2015-02-12
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多