如何在GetResponse

时间:2019-02-21 06:18:42

标签: c# api json.net httpwebresponse

我只是想知道如何在返回值之前检查HTTP状态是否还可以。

这是代码段

var httpResponse = await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        dynamic data = JObject.Parse(responseText);
            shorturl = data.shortLink;
    }
return shorturl;

正在想一些类似的事情

if responseText.Contains(HttpStatusCode.OK)

if (httpResponse.StatusCode == HttpStatusCode.OK)
return shorturl;

任何向我指出正确方向的事情都将不胜感激!

1 个答案:

答案 0 :(得分:1)

内部HttpStatusCode是枚举

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}

然后

HttpStatusCode statusCode;

//your response code

statusCode = response.StatusCode;


if ((int)statusCode == HttpStatusCode.OK)
return shorturl;