Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the 401 Error response using C#?

I have a API which returns the json response. When I call the API from Fiddler it gives me the json reponse as shown below:

enter image description here

JSON Response: enter image description here

Call to API from Web page:

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();
        //}

Now, When the same is executed from a web page it throws exeception '401 Unauthorized Exception'. So, instead of showing error page I want to read the returned JSON error response (as in fiddler) and show to user.

Help Appreciated!

like image 592
SHEKHAR SHETE Avatar asked Nov 15 '25 17:11

SHEKHAR SHETE


1 Answers

Adapted from this answer to ".Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned" by 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();
        }
    }
}
like image 93
SilentTremor Avatar answered Nov 17 '25 10:11

SilentTremor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!