我在我的智慧結束了。我一直在下面的代碼行獲得一個NullReferenceException:NullReferenceException *在ViewBag中設置*值
ViewBag.PaypalError = "we were unable to retreive your cart.";
我知道這是該行 - 我造成它得到一個新的行號文件中的其他地方添加一些代碼,並在我的錯誤的行號改爲遵循它。我知道ViewBag不爲null,因爲我在它之前特別插入了一個if (ViewBag == null)
測試。
爲了使事情變得更爲重要,我有代碼在執行進入導致上述語句的邏輯時發送電子郵件。該電子郵件永遠不會被設置,但這行代碼後來發生,會引發一個異常,並且我從try/catch塊中得到了捕獲它的電子郵件。
我知道我應該避開ViewBag,我有一些重構代碼的想法,在這裏不需要它,但沒有一個告訴我這個異常來自哪裏。
任何想法?測試嘗試?
編輯: 下面是其餘的代碼。這絕對不是從catch塊的代碼,我很自豪,但它應該工作...
public ActionResult PaypalConfirmation(string token, string payerID)
{
try
{
Cart cart = GetCurrentCart();
if (cart == null)
{
// I never get this email.
SendEmail("Paypal confirmation with null cart", "Token: " + token + ".<br><br>", requestData: Request);
if (token != null && token != "")
{
var tempCart = Cart.GetByAlternateOrderNumber(token);
if (tempCart != null)
{
cart = tempCart;
}
else
{
ViewBag.PaypalError = "we were unable to retreive your cart.";
return View("~/Views/Error/PayPal.cshtml");
}
}
else
{
if (ViewBag == null)
{
SendEmail("VIEWBAG WAS NULL", "Token: " + token + ".<br><br>", requestData: Request);
return View("~/Views/Error/PayPal.cshtml");
}
else
{
// Line which errors
ViewBag.PaypalError = "we were unable to retreive your cart.";
return View("~/Views/Error/PayPal.cshtml");
}
}
}
// More execution code here, including the "Everything worked" return.
}
catch (Exception ex)
{
try
{
var isNull = "";
if (ViewBag == null) isNull = "ViewBag was null!<br><br>";
SendEmail("Crash in Paypal Payment", isNull + ex.ToString(), requestData: Request);
return View("~/Views/Error/PayPal.cshtml");
}
catch (Exception ex2)
{
SendEmail("Crash in reporting Paypal Crash!", ex.ToString() + "<br><br>---------------------<br><br>" + ex2.ToString());
return View("~/Views/Error/PayPal.cshtml");
}
}
}
電子郵件:
System.NullReferenceException:對象未設置爲一個對象的實例。 C:############# \ Website \ Controllers \ CartController.cs:Website 137
Timestamp:3/6/2012 10:43:13 AM
IP:#############
URL請求:/ Cart/PaypalConfirmation?token = EC-10L01937X56050826 & PayerID = ###### ######用戶代理:Mozilla的/ 5.0(Macintosh上,英特爾的Mac OS X 10.6; RV:10.0.2)的Gecko/20100101 Firefox的/ 10.0.2
你可以在該行前後添加幾行以供參考? – 2012-03-06 20:21:39
你可以在try catch塊中顯示你的代碼嗎? – 2012-03-06 21:03:09
@JoachimIsaksson,謝謝你的提問。我打算包括它,但忘記了。這裏是。 – Bobson 2012-03-06 21:31:08