日期:2014-05-17  浏览次数:21067 次

C#异步调用后如何看到状态码?
C#异步调用的代码如下:

public class DataRequest
{
    public string paramData=string.Empty;//请求参数
    public string resData=string.Empty;//返回值
    public HttpStatusCode statusCode;//状态记录
    public Exception errorAsync;//记录异步函数中的错误
    public static Encoding dataEncode = Encoding.UTF8;//字符编码方式为UTF8
    public void RequestURL(string url)
    {
        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
        webReq.Method = "POST";
        webReq.ContentType = "application/x-www-form-urlencoded";
        webReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webReq);
    }
    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            byte[] byteArray = dataEncode.GetBytes(paramData);
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();
            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
        }
        catch (Exception ee)
        {
            errorAsync = ee;
         }
    }
    private void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            statusCode=response.StatusCode;
            resData = streamRead.ReadToEnd();
            streamResponse.Close();
  &nb