Url validation attribute marks `localhost` as invalid Url

旧街凉风 提交于 2020-07-18 21:06:16

问题


In our ASP.MVC project we are using DataAnnotations attributes for validation. One of the fields should contains Url and it is marked with [Url] attribute. But if I put http://localhost:13030 into the field value it isn't passing the validation.

Is there any way to use the attribute to define localhost as a valid target?


回答1:


UrlAttribute validates against the RegEx shown in the source code here: https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/UrlAttribute.cs#L46.

http://localhost doesn't match due to its lack of a ..

See this answer for other options: How I can validate urls in C# for localhost.

EDIT: According to the source code, you could add dataAnnotations:dataTypeAttribute:disableRegEx to your AppSettings and set its value to true. This would cause the UrlAttribute validation process to only check that it begins with http://, https:// or ftp://. See Line 33 of the same source file for that.




回答2:


To expand upon Kirk Larkin's answer: The "dataAnnotations:dataTypeAttribute:disableRegEx" app setting is only available since .NET Framework 4.6.1, according to dotnet pull request #668 (re-add ASPNET472CompatDoc).

I also checked by downloading the .NET Framework 4.6 (58 MB .zip) and 4.6.1 RTM (59 MB .zip) source and running the following git diff command.

git diff D:/src/dotnet46/Source/ndp/fx/src/xsp/system/DataAnnotations/DataAnnotations/UrlAttribute.cs D:/src/dotnet461RTM/Source/ndp/fx/src/xsp/system/DataAnnotations/DataAnnotations/UrlAttribute.cs

Indeed, the new-as-of-4.6.1 internal static class AppSettings is what reads the new-as-of-4.6.1 app setting.

And ... My point in adding this answer is that I am out of luck on net452.




回答3:


Just use "127.0.0.1" instead "localhost". E.g http://127.0.0.1:13030



来源:https://stackoverflow.com/questions/45707293/url-validation-attribute-marks-localhost-as-invalid-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!