How to get status code from webclient?

前端 未结 10 1872
轮回少年
轮回少年 2020-11-29 04:03

I am using the WebClient class to post some data to a web form. I would like to get the response status code of the form submission. So far I\'ve found out how

10条回答
  •  無奈伤痛
    2020-11-29 04:48

    There is a way to do it using reflection. It works with .NET 4.0. It accesses a private field and may not work in other versions of .NET without modifications.

    I have no idea why Microsoft did not expose this field with a property.

    private static int GetStatusCode(WebClient client, out string statusDescription)
    {
        FieldInfo responseField = client.GetType().GetField("m_WebResponse", BindingFlags.Instance | BindingFlags.NonPublic);
    
        if (responseField != null)
        {
            HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse;
    
            if (response != null)
            {
                statusDescription = response.StatusDescription;
                return (int)response.StatusCode;
            }
        }
    
        statusDescription = null;
        return 0;
    }
    

提交回复
热议问题