【发布时间】:2015-10-31 01:28:57
【问题描述】:
我的网站宕机了几天,因此我试图在 MVC 应用程序无法访问某些资源的情况下进行一些错误处理,因此如果某些东西不再不可用,整个事情都不必关闭。
此时控制器正试图访问不可用的 viewbag.moreNewProducts。
public ActionResult Index(string search)
{
string[] newProductLines = this.getMoreNewProducts();
string[] newNews = this.getMoreNews();
string[] newPromotions = this.getMorePromotions();
string[] fewerProductLines = this.getLessNewProducts(newProductLines);
ViewBag.moreNewProducts = newProductLines;
ViewBag.moreNews = newNews;
ViewBag.morePromotions = newPromotions;
ViewBag.lessNewProducts = fewerProductLines;
bool disableShowMore = false;
这是我遇到错误的地方:“foreach(newProductLines 中的字符串行)”
public string[] getLessNewProducts(string[] newProductLines)
{
int charCount = 0;
int arrayCount = 0;
string[] displayProductLines = new string[6];
bool continueWriting;
if (newProductLines == null)
{
foreach (string line in newProductLines)
{
continueWriting = false;
for (int i = 0; charCount < 250 && i < line.Length && arrayCount < 5; i++)
{
string index = newProductLines[arrayCount].Substring(i, 1);
displayProductLines[arrayCount] += index;
charCount++;
continueWriting = true;
}
if (continueWriting == true)
{
arrayCount++;
}
}
string[] LessNewProducts = new string[arrayCount];
for (int d = 0; d < arrayCount; d++)
{
LessNewProducts[d] = displayProductLines[d];
}
return LessNewProducts;
}
else
{
return null;
}
}
我如何绕过 if else 语句,这样整个事情就不会崩溃?
【问题讨论】:
-
您是否尝试将其包装在 try and catch 中?
标签: asp.net-mvc-4 error-handling nullreferenceexception