【问题标题】:RazorPages: undefined key in viewData not throwing exceptionRazorPages:viewData 中未定义的键不抛出异常
【发布时间】:2020-04-29 17:54:48
【问题描述】:

我在 ASP.NET 核心中使用 Razor Pages 作为学习练习,当我尝试在 viewData 中使用未定义的键时,我注意到的一件事是没有引发异常。我假设这是有意的,但我想知道......为什么?我应该如何检测此类错误?似乎很容易打错字,而且在为时已晚之前很难注意到。一个例子:

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace Infodawn.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            // doesn't throw exception, even though viewData["bar"] is undefined:
            ViewData["foo"] = ViewData["bar"];

            // throws exception, as expected:
            Dictionary<string, int> dict = new Dictionary<string, int>();
            int a = dict["bar"];
        }
    }
}

【问题讨论】:

    标签: asp.net razor razor-pages


    【解决方案1】:

    如果没有设置 ViewData 项,它将是null。因此,您应该在尝试使用 ViewData 项目之前测试 null:

    if(ViewData["bar"] != null)
    {
        //
    }
    

    在使用任何依赖于“魔术字符串”(例如字符串索引器)的 API 时,存在错误进入代码并导致错误等的固有风险。一种通用的解决方案是使用常量来表示键值.

    在 Razor Pages 中,建议使用 PageModel properties 将数据从控制器传递到视图而不是 ViewData。

    【讨论】:

      猜你喜欢
      • 2010-11-16
      • 1970-01-01
      • 2016-03-26
      • 2021-03-11
      • 2011-05-30
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      相关资源
      最近更新 更多