在我们的 ASP.MVC 项目中,我们使用 DataAnnotations 属性进行验证。其中一个字段应包含 Url,并用 [Url]
属性标记。但是,如果我将 http://localhost:13030
放入字段值中,它就不会通过验证。
有什么方法可以使用该属性将 localhost
定义为有效目标吗?
最佳答案
UrlAttribute
根据此处源代码中显示的 RegEx 进行验证:https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/UrlAttribute.cs#L46 .
http://localhost
不匹配,因为它缺少 .
。
有关其他选项,请参阅此答案:How I can validate urls in C# for localhost .
编辑:根据源代码,您可以将 dataAnnotations:dataTypeAttribute:disableRegEx
添加到您的 AppSettings 并将其值设置为 true
。这将导致 UrlAttribute
验证过程仅检查它是否以 http://
、https://
或 ftp://
。参见 Line 33相同的源文件。
关于c# - Url 验证属性将 `localhost` 标记为无效 Url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45707293/