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