我需要確定用戶列表是否位於第三方用戶目錄中。我正在用C#.NET 4.0寫這個方法。用戶列表超過2700個條目。訪問此用戶目錄的API使用REST返回用戶信息。如果用戶不在目錄中,則對HttpWebRequest的響應是404錯誤。我發現了WebException錯誤。HttpWebRequest響應返回404錯誤後繼續
問題是我一次只能得到一個用戶的用戶信息,所以我想做一個for循環來通過用戶列表。但是,當發生404錯誤時,它會跳出循環。有什麼方法可以捕捉到404錯誤,並繼續與下一個用戶的循環?
這是我的代碼:
public void GetRecipientDataFromCortext()
{
SqlConnection SqlConn = null;
CortextUser objCortextResult;
try
{
string strStoredProcedure = "PagingToolGetRecipientsAndDevices";
DataTable tdtRecipientData = new DataTable("RecipientData");
//Create a datatable to store final results
DataTable tdtCortextResultData = new DataTable("CortextResults");
tdtCortextResultData.Columns.Add("RecipientID", typeof(int));
tdtCortextResultData.Columns.Add("DeviceTypeID", typeof(int));
tdtCortextResultData.Columns.Add("DeviceAddress", typeof(string));
tdtCortextResultData.Columns.Add("CUID", typeof(string));
tdtCortextResultData.Columns.Add("InviteStatus", typeof(string));
tdtCortextResultData.Columns.Add("IsEnabled", typeof(bool));
tdtCortextResultData.Columns.Add("FirstName", typeof(string));
tdtCortextResultData.Columns.Add("LastName", typeof(string));
tdtCortextResultData.Columns.Add("MiddleName", typeof(string));
tdtCortextResultData.Columns.Add("HonorificPrefix", typeof(string));
tdtCortextResultData.Columns.Add("HonorificSuffix", typeof(string));
tdtCortextResultData.Columns.Add("Email", typeof(string));
tdtCortextResultData.Columns.Add("Mobile", typeof(string));
tdtCortextResultData.Columns.Add("Pager", typeof(string));
string strSqlConnection = ConfigurationManager.ConnectionStrings[CONNECTION_STRING].ConnectionString;
//Get the recipient list from the database
using (SqlConn = new SqlConnection(strSqlConnection))
{
using (SqlCommand SqlCmd = new SqlCommand(strStoredProcedure, SqlConn))
{
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlConn.Open();
using (SqlDataAdapter dataReturned = new SqlDataAdapter(SqlCmd))
{
dataReturned.Fill(tdtRecipientData);
}
}
}
//For loop to make a call to cortext to get properties of this device
string tstrPropertyValue = string.Empty;
string tstrProperty = string.Empty;
int tiDeviceTypeID;
int tiRecipientID;
//This is the for loop to check each recipient to see if he/she is in the directory
foreach (DataRow row in tdtRecipientData.Rows)
{
tstrPropertyValue = row["Address"].ToString();
tiDeviceTypeID = Convert.ToInt32(row["DeviceTypeID"].ToString());
tiRecipientID = Convert.ToInt32(row["RecipientID"].ToString());
//Insert into the Cortext table initial values first
//This inserts into a database table the user to check.
//This table is used to get the initial recipient list.
//Any users in this table are not in the list.
InsertCortextInformation(tiRecipientID, tiDeviceTypeID, tstrPropertyValue);
switch (tiDeviceTypeID)
{
case 1:
tstrProperty = "mobile";
break;
case 2:
tstrProperty = "email";
break;
case 3:
tstrProperty = "pager";
break;
default:
break;
}
//Results from cortext call add to data table
//User not in the directory results in this method call to return a 404 error.
//Exception breaks out of the loop
objCortextResult = GetCortextUserInformation(tstrProperty, tstrPropertyValue);
//Add results to datatable
DataRow newRow = tdtCortextResultData.NewRow();
newRow["RecipientID"] = Convert.ToInt32(row["RecipientID"].ToString());
newRow["DeviceTypeID"] = Convert.ToInt32(row["DeviceTypeID"].ToString());
newRow["DeviceAddress"] = row["Address"].ToString();
newRow["CUID"] = objCortextResult.CUID;
newRow["InviteStatus"] = objCortextResult.inviteStatus;
newRow["IsEnabled"] = objCortextResult.isEnabled;
newRow["FirstName"] = objCortextResult.userFirstName;
newRow["LastName"] = objCortextResult.userLastName;
newRow["MiddleName"] = objCortextResult.userMiddleName;
newRow["HonorificPrefix"] = objCortextResult.userHonorificPrefix;
newRow["HonorificSuffix"] = objCortextResult.userHonorificSuffix;
newRow["Email"] = objCortextResult.email;
newRow["Mobile"] = objCortextResult.mobile;
newRow["Pager"] = objCortextResult.pager;
tdtCortextResultData.Rows.Add(newRow);
}
//Insert data table results into Paging Tool table, PagingToolCortextInfo
int tiRecID, tiDeviceID;
bool tbIsEnabled;
foreach (DataRow row in tdtCortextResultData.Rows)
{
tiRecID = Convert.ToInt32(row["RecipientID"].ToString());
tiDeviceID = Convert.ToInt32(row["DeviceTypeID"].ToString());
tbIsEnabled = Convert.ToBoolean(row["IsEnabled"].ToString());
UpdateCortextInformation(tiRecID, tiDeviceID, row["DeviceAddress"].ToString(),
row["CUID"].ToString(), row["InviteStatus"].ToString(), tbIsEnabled,
row["FirstName"].ToString(), row["LastName"].ToString(), row["MiddleName"].ToString(),
row["HonorificPrefix"].ToString(), row["HonorificSuffix"].ToString(),
row["Email"].ToString(), row["Mobile"].ToString(), row["Pager"].ToString());
}
}
//Catches the HttpWebResponse errors like 404
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
string errorMessage = string.Format("Error code: {0} ", httpResponse.StatusCode);
// System.Diagnostics.Debug.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
errorMessage += text;
//
System.Diagnostics.Debug.WriteLine(text);
logger.ErrorException(errorMessage, e);
}
}
}
throw;
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
throw;
}
finally
{
if (SqlConn != null)
{
SqlConn.Close();
}
}
}
那麼,有沒有什麼辦法可以繼續在for循環中調用HTTP響應返回404錯誤後並獲得下一個用戶?
我想承認404錯誤,並繼續在for循環中獲取所有用戶。
謝謝。
放置一個'try {} catch {}'確定拋出異常的方法。 – AgentFire
我有'WebException' catch捕獲404錯誤。我的問題是,它把我扔出for循環,我不能得到下一個用戶。如何避免404錯誤被拋出時退出for循環?我想承認錯誤並繼續進行循環。 –
在你的循環內放置一個'try {} catch {} ** **範圍出引發異常的方法。 – AgentFire