문제

This code works, but may be only as performant as a 112-year-old alcoholic:

try
{
    const string uri = "http://localhost:28642/api/departments/Count";
    var webRequest = (HttpWebRequest)WebRequest.Create(uri);
    webRequest.Method = "GET";
    var webResponse = (HttpWebResponse)webRequest.GetResponse();
    if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
    {
        var reader = new StreamReader(webResponse.GetResponseStream());
        string s = reader.ReadToEnd();
        MessageBox.Show(string.Format("Content from HttpWebRequest is {0}", s));
    }
    else
    {
        MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

The Web API REST method being called simply returns an int. Is this StreamReader jazz overkill for getting that one simple value? If so, what is the preferred method?

도움이 되었습니까?

해결책

Jon Skeet is on the case - WebClient.DownloadString is easy as (eating) pie:

var client = new WebClient();
MessageBox.Show(client.DownloadString("http://localhost:28642/api/departments/Count"));

IOW, the code I originally showed is definitely overkill for retrieving a scalar value.

UPDATE

Better yet:

private void buttonGetDeptCount2_Click(object sender, EventArgs e)
{
    MessageBox.Show(GetScalarVal("http://localhost:28642/api/departments/Count"));
}

private string GetScalarVal(string uri)
{
    var client = new WebClient();
    return client.DownloadString(uri);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top