我正在使用asp.net,我想将以下语句转换为c#
Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
st = reader.ReadToEnd()
End Using
Run Code Online (Sandbox Code Playgroud)
如果有人知道,请告诉我.先感谢您.
那么,字面翻译将是:
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
然而,如果响应不是一个HttpWebResponse认为仍然会失败-只是一个NullReferenceException.我更喜欢演员:
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
或者要非常小心,即使它不是网络响应,也会清除响应:
using (WebResponse response = request.GetResponse())
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
StreamReader reader = new StreamReader(httpResponse.GetResponseStream());
st = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
......但WebResponse已经包含了GetResponseStream,所以没有必要首先施展HttpWebResponse,说实话.
| 归档时间: |
|
| 查看次数: |
340 次 |
| 最近记录: |