我如何在C#中验证localhost的URL [英] How I can validate urls in C# for localhost
本文介绍了我如何在C#中验证localhost的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在MVC中使用UrlAttribute
I am using UrlAttribute in MVC
但不接受localhost网址,例如 http://localhost/GCWeb
but its not accepting the localhost urls e.g http://localhost/GCWeb
[Url(ErrorMessage = "please_enter_valid_ftp_url", ErrorMessage = null)]
public string Url { get; set; }
这会验证网址,但不会验证本地主机的网址.
This validates the urls but not for localhost urls.
我该怎么做?
推荐答案
我还建议创建一个自定义验证器属性类.但是我想使用System.Uri类进行验证,而不是使用自定义个人正则表达式.
I also suggest to create a custom validator attribute class. But I'd like to use System.Uri class to validate instead of custom personal regex.
public class UriAttribute: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Uri uri;
bool valid = Uri.TryCreate(Convert.ToString(value), UriKind.Absolute, out uri);
if (!valid)
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
通过使用System.Uri类,我们可以排除自身正则表达式出错的机会.
By using System.Uri class, we can leave out chances of error for own regex.
这篇关于我如何在C#中验证localhost的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文