asp.net .Net上有URL验证器吗?

33qvvth1  于 2023-10-21  发布在  .NET
关注(0)|答案(7)|浏览(210)

在.Net、ASP.NET或ASP.NetMVC中是否有验证URL的方法?

cbeh67ev

cbeh67ev1#

您可以使用Uri.TryCreate来验证URL:

  1. public bool IsValidUri(string uri)
  2. {
  3. Uri validatedUri;
  4. return Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out validatedUri);
  5. }

注解表明TryCreate只是将异常处理向下移动了一级。但是,我检查了源代码,发现情况并非如此。TryCreate内部没有try/catch,它使用了一个自定义的解析器,不应该抛出。

toe95027

toe950272#

到目前为止提供的答案不检查方案,允许各种不需要的输入,这可能使您容易受到JavaScript注入的攻击(请参阅TheCloudlessSky的评论)。
URI只是对象的唯一标识。“C:\Test”是一个有效的URI。
在我的项目中,我使用了以下代码:

  1. /// <summary>
  2. /// Validates a URL.
  3. /// </summary>
  4. /// <param name="url"></param>
  5. /// <returns></returns>
  6. private bool ValidateUrl(string url)
  7. {
  8. Uri validatedUri;
  9. if (Uri.TryCreate(url, UriKind.Absolute, out Uri validatedUri)) //.NET URI validation.
  10. {
  11. //If true: validatedUri contains a valid Uri. Check for the scheme in addition.
  12. return (validatedUri.Scheme == Uri.UriSchemeHttp || validatedUri.Scheme == Uri.UriSchemeHttps);
  13. }
  14. return false;
  15. }

定义您将允许的方案并相应地更改代码。

展开查看全部
kqqjbcuj

kqqjbcuj3#

你可以使用Uri.IsWellFormedUriString,不需要创建自己的函数:

  1. public static bool IsWellFormedUriString(string uriString, uriKind uriKind);

在哪里uriKind可以:

  1. UriKind.RelativeOrAbsolute
  2. UriKind.Absolute
  3. UriKind.Relative

有关更多信息,请参阅:http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx

wbgh16ku

wbgh16ku4#

如果你需要Arjan提供的VB.Net中的漂亮代码,

  1. 'Validates a URL.
  2. Function ValidateUrl(url As String) As Boolean
  3. Dim validatedUri As Uri = Nothing
  4. If (Uri.TryCreate(url, UriKind.Absolute, validatedUri)) Then
  5. Return (validatedUri.Scheme = Uri.UriSchemeHttp Or validatedUri.Scheme = Uri.UriSchemeHttps)
  6. End If
  7. Return False
  8. End Function
dluptydi

dluptydi5#

比使用try/catch功能更快的方法(可能)是使用Regex。如果你必须验证1000个URL,多次捕获异常会很慢。
这里是a link to sample Regex-使用谷歌找到更多。

w6mmgewl

w6mmgewl6#

ASP.Net核心模型验证

在ASP.NET Core中,验证通常作为模型绑定的一部分(因此,在官方文档中称为模型验证)
假设你有一个端点,比如:

  1. public AppController: ControllerBase
  2. {
  3. public async Task<IActionResult> GetValues(InputDto input) { ... }
  4. }

你的InputDto模型是:

  1. public class InputDto
  2. {
  3. public string DownloadLink {get; set;}
  4. }

您的要求是验证DownloadLink的给定值应该是格式良好的URL。
您可以使用为此目的而设计的内置属性:

  1. using System.ComponentModel.DataAnnotations;
  2. public class InputDto
  3. {
  4. [Url]
  5. public string DownloadLink {get; set;}
  6. }
展开查看全部
tgabmvqs

tgabmvqs7#

  1. static bool IsValidUri(string urlString) {
  2. try {
  3. new Uri(urlString);
  4. return true;
  5. } catch {
  6. return false;
  7. }
  8. }

相关问题