如何使用C#处理401错误响应?

时间:2015-07-29 06:59:02

标签: c# asp.net json exception-handling http-status-code-401

我有API,返回json response。 当我从API拨打Fiddler时,它会给我json reponse 如下图所示:

enter image description here

JSON响应: enter image description here

从网页调用API:

protected void FinalCall()
    {

       // try
       // {
            string url = txtdomainURL.Text.Trim(); 
            string apiname = txtAPIname.Text.Trim();
            string apiURL = apiname+"/"+txtStoreID.Text.Trim()+"/"+txtSerialNo.Text.Trim(); //"duediligence/1/45523354232323424";// 990000552672620";//45523354232323424";
            //duediligence/1/45523354232323424 HTTP/1.1
            string storeID = txtStoreID.Text.Trim();//Test Store ID:1 Live Store ID: 2
            string partnerID = txtPartnerID.Text.Trim();// "1";
            string scretKey = txtSecretKey.Text.Trim();// "234623ger787qws3423";
            string requestBody = txtRequestBody.Text.Trim(); //"{\"category\": 8}";
            string data = scretKey + requestBody;


            string signatureHash = SHA1HashStringForUTF8String(data);
            lblSignatureHash.Text = signatureHash;
            String userName = partnerID;
            String passWord = signatureHash;
            string credentials = userName + ":" + passWord;//Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
            var dataString = JsonConvert.SerializeObject(requestBody); //JsonConvert.SerializeObject(requestBody);
            var bytes = Encoding.Default.GetBytes(dataString);


            WebClient client = new WebClient();
            string base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
            client.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
            lblBase64.Text = base64;

            client.Headers.Add(HttpRequestHeader.Accept, "application/json");
            client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
            //string response = cli.UploadString(url + apiURL, dataString); //"{some:\"json data\"}"
            string completeURLRequest = url + apiURL;

            //I GET ERROR HERE 
            var result = client.DownloadString(completeURLRequest);
            //CODE below this line is not executed

            //Context.Response.TrySkipIisCustomErrors = true;
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var jsonObject = serializer.DeserializeObject(result.ToString());
            //var result1 = client.UploadData(completeURLRequest, "POST", bytes);
            Response.Write(result);
            txtwebresponse.Text = jsonObject.ToString();
        //}

现在,当从网页执行相同操作时,它会抛出exeception '401 Unauthorized Exception'。因此,我没有显示错误页面,而是希望阅读返回的JSON错误响应(如在fiddler中)并向用户显示。

帮助感谢!

2 个答案:

答案 0 :(得分:9)

this answer改编自".Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned"Jon Skeet

try
{
    using (WebResponse response = request.GetResponse())
    {
        Console.WriteLine("You will get error, if not do the proper processing");
    }
}
catch (WebException e)
{
    using (WebResponse response = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse) response;
        Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
        using (Stream data = response.GetResponseStream())
        using (var reader = new StreamReader(data))
        {
            // text is the response body
            string text = reader.ReadToEnd();
        }
    }
}

答案 1 :(得分:0)

稍微改变SilentTremor的答案。结合using语句会使代码短一些。

 catch (WebException ex)
 {
            HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
            using (WebResponse response = ex.Response)
            using (Stream data = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(data))
            {
                string errorMessage = reader.ReadToEnd();
            }
 }