簡體   English   中英

從Web API REST調用中獲取Int是否過於刻薄?

[英]Is This Overkill to Retrieve an Int from a Web API REST call?

該代碼有效,但可能僅與112歲的酒精飲料一樣有表現:

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);
}

調用的Web API REST方法僅返回一個int。 StreamReader爵士樂是為了獲得一個簡單的價值而矯kill過正? 如果是這樣,首選的方法是什么?

喬恩·斯凱特(Jon Skeet)就是案例-WebClient.DownloadString很容易(吃)餡餅:

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

IOW,我最初顯示的代碼對於檢索標量值肯定是過大的。

更新

更好的是:

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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM