C#post API方法错误处理 [英] C# post API method error handling

查看:147
本文介绍了C#post API方法错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如果状态是200,那么它是正确的,否则它会重定向到catch方法,这样我就无法在api上获取错误详细信息响应。



On这一行

in the below code if status is 200 then it is ok else it redirects to catch method so that i cannot fetch the error detail response on api.

On this line

var response = client.UploadString(webApiUrl, serialisedData);



如果状态重定向到catch方法api不是200.




it redirects to catch method if status of api is not 200.

public object postWebApi(object data, Uri webApiUrl, string id, string password)
       {
           // Create a WebClient to POST the request
           WebClient client = new WebClient();
           client.Encoding = Encoding.UTF8;

           // Set the header so it knows we are sending JSON
           client.Headers[HttpRequestHeader.ContentType] = "application/json";

           // Serialise the data we are sending in to JSON
           string serialisedData = JsonConvert.SerializeObject(data);

           string auth = string.Format("{0}:{1}", id, password);
           string enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
           string cred = string.Format("{0} {1}", "Basic", enc);

           client.Headers[HttpRequestHeader.Authorization] = cred;
           // Make the request
           var response = client.UploadString(webApiUrl, serialisedData);

           // Deserialise the response into a GUID
           return JsonConvert.DeserializeObject(response);
       }





我尝试过:



如果成功,请提供帮助,如果回复状态为400或其他无法读取api的回复,则可以提供帮助。



What I have tried:

Please help in case of successful it is fine if the status of response is 400 or other could not read the respnse of api.

推荐答案

var response = string.Empty;
            try
            {
                response = client.UploadString(webApiUrl, serialisedData);
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                }
            }





如果发现异常,我们将收到回复。



If exception is found then we will get the response.


这篇关于C#post API方法错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆