programing tip

System.Net.WebException HTTP 상태 코드

itbloger 2020. 6. 19. 19:53
반응형

System.Net.WebException HTTP 상태 코드


에서 HTTP 상태 코드를 얻는 쉬운 방법이 System.Net.WebException있습니까?


아마도 이런 식으로 ...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

사용하여 널 조건 연산자를 ( ?.) 당신은 단 한 줄의 코드로 HTTP 상태 코드를 얻을 수 있습니다 :

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

변수 status는를 포함합니다 HttpStatusCode. HTTP 상태 코드가 전송되지 않는 네트워크 오류와 같은보다 일반적인 오류가 발생 status하면 null이됩니다. 이 경우을 ex.Status얻을 수 있는지 검사 할 수 있습니다 WebExceptionStatus.

오류가 발생했을 때 설명 문자열 만 기록하려면 null-coalescing 연산자 ( ??)를 사용하여 관련 오류를 얻을 수 있습니다.

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

404 HTTP 상태 코드의 결과로 예외가 발생하면 문자열에 "NotFound"가 포함됩니다. 반면에 서버가 오프라인 상태이면 문자열에 "ConnectFailure"등이 포함됩니다.

HTTP 하위 상태 코드를 얻는 방법을 알고 싶은 사람은 불가능합니다. 서버에만 로그온되어 클라이언트로 전송되지 않는 Microsoft IIS 개념입니다.


이것은 WebResponse가 HttpWebResponse 인 경우에만 작동합니다.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

(질문이 오래되었다는 것을 알고 있지만 Google의 인기 히트작 중 하나입니다.)

응답 코드를 알고 싶은 일반적인 상황은 예외 처리입니다. C # 7부터 예외가 술어와 일치하는 경우 패턴 일치를 사용하여 실제로 catch 절을 입력 할 수 있습니다.

catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
     doSomething(response.StatusCode)
}

This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.


You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(WebException we)
{
    if (we.Response is HttpWebResponse)
    {
        HttpWebResponse response = (HttpWebResponse)we.Response;
        return response.StatusCode;
    }
    return null;
}

I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.

Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.

참고URL : https://stackoverflow.com/questions/3614034/system-net-webexception-http-status-code

반응형