c# - 如何将错误从 TypeConverter 传递到 ModelState 错误
问题描述
我已经实现了TypeConverter
从查询中的字符串反序列化类型。
类型 containsGuid
和Guid
in string 可能无效,因此我想将错误传递给 ModelState。
我尝试throw new ArgumentException("my message")
,并且它正在工作,但是来自异常的错误消息没有传递给ModelError.ErrorMessage
. 有什么方法可以将错误消息传递到ModelError.ErrorMessage
或者我只能从中获取消息ModelError.Exception.Message
?
解决方案
好的,我知道您要做什么。
由于内置的 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); } ...
有关更多详细信息,请参阅源代码:
推荐阅读
- cordova - Cordova:媒体插件录制音频空文件
- sql-server - 获取同一个表中通过外键连接的所有行
- wordpress - 统计 WordPress 网站的访问次数
- python - 如何覆盖列表并将列表附加到字典
- javascript - material-ui-dropzone,DropzoneAreaBase 不显示添加的文件预览
- r - 从 Shiny 应用程序生成可下载的报告
- javascript - JavaScript:根据对象属性中的空间拆分数组中的对象
- sql - 加密 SQL Server 中视图列(非表)中的数据
- python - 有人知道如何一次下载一个文件吗
- powershell - 多个文件名称中的Powershell偏移数,由常量表示