ModelStateDictionary不包含CopyTo的定义

时间:2016-07-05 08:11:48

标签: c# asp.net-core asp.net-core-mvc asp.net-core-1.0

在ASP.NET Core RC 1(完整的.NET Framework)中,我可以使用以下代码:

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.ModelBinding;
using Newtonsoft.Json;

namespace MyProject.Classes.Filters.ModelState
{
    public class SetTempDataModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            var controller = filterContext.Controller as Controller;
            if (controller != null)
            {
                var modelState = controller.ViewData.ModelState;
                if (modelState != null)
                {
                    var dictionary = new KeyValuePair<string, ModelStateEntry>[modelState.Count];
                    modelState.CopyTo(dictionary, 0);
                    var listError = dictionary.ToDictionary(m => m.Key, m => m.Value.Errors.Select(s => s.ErrorMessage).FirstOrDefault(s => s != null));
                    controller.TempData["ModelState"] = JsonConvert.SerializeObject(listError);
                }
            }
        }
    }
}

但是在ASP.NET Core 1.0(完整的.NET Framework)中,会发生错误:

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;

namespace MyProject.Models.ModelState
{
    public class SetTempDataModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            var controller = filterContext.Controller as Controller;
            if (controller != null)
            {
                var modelState = controller.ViewData.ModelState;
                if (modelState != null)
                {
                    var dictionary = new KeyValuePair<string, ModelStateEntry>[modelState.Count];
                    modelState.CopyTo(dictionary, 0);
                    modelState = dictionary.[0];
                    var listError = dictionary.ToDictionary(m => m.Key, m => m.Value.Errors.Select(s => s.ErrorMessage).FirstOrDefault(s => s != null));
                    controller.TempData["ModelState"] = JsonConvert.SerializeObject(listError);
                }
            }
        }
    }
}
  

'ModelStateDictionary'不包含'CopyTo'和的定义   没有扩展方法'CopyTo'接受类型的第一个参数   可以找到'ModelStateDictionary'(你是否错过了使用   指令或程序集引用?)

也许我需要将一个新引用连接到ASP.NET Core RC 1中不需要的程序集?

1 个答案:

答案 0 :(得分:1)

ModelStateDictionary未实现IDictionary<,>因此没有CopyTo方法。在您的情况下,您可以用

替换您的代码
var listErrorr = modelState.ToDictionary(
  m => m.Key, 
  m => m.Value.Errors
    .Select(s => s.ErrorMessage)
    .FirstOrDefault(s => s != null)
); 

这应该在功能上与您在原始代码段中所做的相同。