我正在编写一个程序来检查凭单号是否有效,并且我发现很难从我正在使用的REST API提取错误消息。c#对我来说是很新的,通常是VB.net,但目前正在为某人覆盖。
基本上我有一个HttpWebReqest
和HttpWebResponse
对象,并使用下面的代码,我发出一个成功的请求,并得到一个响应。
当一切顺利时,没有问题,但例如,如果凭证无效或网站无效,我应该得到这样的响应,就像我在Postman中所做的那样,参见下面的示例。
{
"message": "The given data was invalid.",
"errors": {
"voucher_no": [
"Sorry, that voucher number is invalid."
]
}
}
相反,我被抛出到Try/Catch..异常
错误信息Error 422 unprocessable entity,
没有进一步的细节或对象来检查上面的真实消息?
try
{
using (HttpWebResponse response = mywebrequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
// I am unable to get to this part of the Code to process the Error because Try/Catch is executed instead ...
}
else
{
Stream dataStream1 = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream1);
responseFromServer = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
msgbox = new MsgBox_UI("Error", "Web Server Returned an Error", "There is a problem with this Voucher. It may be Expired or invalid at this time.", 1, false, 28);
msgbox.ShowDialog();
break;
}
如果有人有任何想法,我如何才能使这个工作,这将是一个很大的帮助。
这是设计的,当请求返回一个'不成功的'状态码时,GetResponse
将抛出一个WebException
(1)。
- 您可以检查
WebException
上的Status
属性以获得statuscode - 和webserver响应的
Response
属性
首先最好使用HttpClient类。
这段代码应该为你工作(如果不让我知道):
private async Task<string> GetExtensionToken()
{
string url = "https://YourApi.com";
try
{
var httpclient = new HttpClient();
using (HttpResponseMessage response = httpclient.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
string Is_Not_Valid = "invalid";
if (result.Contains(Is_Not_Valid))
{
string token = "Whatever you want to extract if error page" ;
return token;
}
else
{
string token = "Whatever you want to extract if succeeded" ; return token;
}
}
}
}
catch (Exception ex)
{
return "Error from catch ";
}
}
用法:
private async void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = await GetExtensionToken();
}
好的,所以我采纳了上面Peter的建议,决定使用HttpClient()。
然而,我实际上使用了ressharp,并在我的项目中安装了Nuget包RestSharp。(主要原因是邮差代码片段给了我确切的代码使用。
然后就像做梦一样。
我没有做Async所以这里是我发现修复我的问题后添加
using RestSharp;
var client = new RestClient("https://api.voucherURL.uk/redeem");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Smart-Auth", "sk_xxxxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("Accept", "application/json");
request.AddParameter("application/json", "{n "voucher_no":"JY584111E3",n "site_id": 14n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);