首页 > 解决方案 > 如何将错误从 TypeConverter 传递到 ModelState 错误

问题描述

我已经实现了TypeConverter从查询中的字符串反序列化类型。

类型 containsGuidGuidin string 可能无效,因此我想将错误传递给 ModelState。

我尝试throw new ArgumentException("my message"),并且它正在工作,但是来自异常的错误消息没有传递给ModelError.ErrorMessage. 有什么方法可以将错误消息传递到ModelError.ErrorMessage或者我只能从中获取消息ModelError.Exception.Message

标签: c#.netasp.net-coretypeconverter

解决方案


好的,我知道您要做什么。

由于内置的​​ ModelBinder 将捕获 的内部异常FormatException,为了设置ModelError.ErrorMessage,我们可以抛出(或重新抛出)一个新的异常FormatException。例如,

公共类 MyConverter : TypeConverter
{
    ...

    公共覆盖对象 ConvertFrom(ITypeDescriptorContext 上下文,CultureInfo 文化,对象值)
    {
        如果(值是字符串)
        {
            尝试{
                ...
                返回新的 MyClass(x);
            }
            catch(Exception e){                  
                throw new FormatException("哎哟:某事发生了");   // 抛出一个 FormatException
             }
        }
        return base.ConvertFrom(context,culture,value);
    }
    ...

有关更多详细信息,请参阅源代码


推荐阅读