我需要确定用户列表是否在第三方用户目录中。我在C#.NET 4.0中编写该方法。用户列表超过2700个条目。访问此用户目录的API使用REST返回用户信息。如果用户不在目录中,则对HttpWebRequest的响应是404错误。我抓住了WebException错误。
问题是我一次只能获得1个用户的用户信息,所以我想通过用户列表进行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();
}
}
}
那么,在调用Http响应返回404错误并获得下一个用户之后,有没有办法在for循环中继续?
我想承认404错误,并继续在for循环中获取所有用户。
感谢。
答案 0 :(得分:1)
使用您的代码可以很容易地实现这一点:)
换行:
objCortextResult = GetCortextUserInformation(tstrProperty, tstrPropertyValue);
在try catch中:
var isNotFound = false;
try {
objCortextResult = GetCortextUserInformation(tstrProperty, tstrPropertyValue);
}
catch(WebException ex) {
if(((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
isNotFound = true;
}
else {
throw;
}
}
if (isNotFound) continue;
...
状态码404的继续将进入循环的下一次迭代并实现所需的行为。
如果您还有其他需要,请告诉我们!
答案 1 :(得分:0)
你可以尝试保持try catch for循环吗? 您也可以尝试为每个或TPL并行执行此操作。