[C#] 문자열이 유효한 HTTP URL인지 확인하는 방법

거기 있습니다 Uri.IsWellFormedUriStringUri.TryCreate방법은, 그러나 그들은 반환하는 것 true파일 경로 등을 위해

입력 유효성 검사를 위해 문자열이 유효한 HTTP URL인지 확인하려면 어떻게해야합니까?



답변

HTTP URL의 유효성을 검사하려면 다음을 시도하십시오 ( uriName테스트하려는 URI 임).

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
    && uriResult.Scheme == Uri.UriSchemeHttp;

또는 HTTP 및 HTTPS URL을 모두 유효한 것으로 승인하려면 (J0e3gan의 설명에 따라) :

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);


답변

이 방법은 http와 https 모두에서 잘 작동합니다. 한 줄만 🙂

if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))

MSDN : IsWellFormedUriString


답변

    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }

용법:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

업데이트 : (한 줄의 코드) 감사합니다 @GoClimbColorado

public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;

용법:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}


답변

여기에 모든 해답 중 하나를 허용 다른 제도와의 URL (예 : file://, ftp://) 또는로 시작하지 않는 사람이 읽을 수있는 URL을 거부 http://하거나 https://(예 www.google.com) 사용자 입력을 처리 할 때 좋은하지 않은 .

내가하는 방법은 다음과 같습니다.

public static bool ValidHttpURL(string s, out Uri resultURI)
{
    if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
        s = "http://" + s;

    if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
        return (resultURI.Scheme == Uri.UriSchemeHttp ||
                resultURI.Scheme == Uri.UriSchemeHttps);

    return false;
}

용법:

string[] inputs = new[] {
                          "https://www.google.com",
                          "http://www.google.com",
                          "www.google.com",
                          "google.com",
                          "javascript:alert('Hack me!')"
                        };
foreach (string s in inputs)
{
    Uri uriResult;
    bool result = ValidHttpURL(s, out uriResult);
    Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}

산출:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False


답변

Uri.TryCreate확인할 수 있습니다 Uri.Scheme그것은 HTTP 경우 (들)을 참조하십시오.


답변

그것을보십시오 :

bool IsValidURL(string URL)
{
    string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}

다음과 같은 URL을 허용합니다.

  • http (s) : //www.example.com
  • http (s) : //stackoverflow.example.com
  • http (s) : //www.example.com/page
  • http (s) : //www.example.com/page? id = 1 & product = 2
  • http (s) : //www.example.com/page#start
  • http://www.example.com:8080
  • http : //s.127.0.0.1
  • 127.0.0.1
  • www.example.com
  • example.com

답변

이것은 bool을 반환합니다.

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)