我正在创建一个ASP.NET MVC应用程序,我希望它在发生错误时我会调用另一个加载不同视图的操作。
public ActionResult Invoices()
{
invoiceClass invoice = getInvoice();
//do stuff with invoice
}
public invoiceClass getInvoice()
{
invoiceClass invoice = new invoiceClass();
try
{
// Do stuff
}
catch(exception e)
{
return RedirectToAction("Index");
}
return invoice;
}
我有一个与此非常类似的方法,当我单步执行代码时,异常被捕获并且它命中重定向调用然后转到返回并继续而不重定向。我错过了一些明显的东西吗?
答案 0 :(得分:3)
如果这是一个HTTP入口点,您应该返回ActionResult
。
public ActionResult stuff()
{
try
{
// Do stuff
}
catch (Exception e)
{
//Return a RedirectResult
return RedirectToAction("Index");
}
//Return a JsonResult
//Example: return the JSON data { "number": 1 }
return Json(new { number = 1 });
}
根据您刚刚编辑的内容,以下是我如何处理您的问题。
public ActionResult Invoices()
{
try
{
invoiceClass invoice = getInvoice();
//do stuff with invoice
return Json(...);
}
catch
{
//Catch the exception at the top level
return RedirectToAction("Index");
}
}
public invoiceClass getInvoice()
{
invoiceClass invoice = new invoiceClass();
// Do stuff; possibly throw exception if something goes wrong
return invoice;
}
答案 1 :(得分:0)
您错过了返回
return RedirectToAction("Index");
不要忘记将您的退货类型更改为ActionResult
答案 2 :(得分:0)
所以我设法找到了解决这个问题的方法,但我确信会有更好的方法。
public ActionResult Invoices()
{
try{
invoiceClass invoice = getInvoice();
//do stuff with invoice
}catch (exception e){
return RedirectToAction("Index");
}
}
public invoiceClass getInvoice()
{
invoiceClass invoice = new invoiceClass();
try
{
// Do stuff
}
catch(exception e)
{
index(); //<--the action result
}
return invoice;
}
调用index()运行该方法,然后在Invoices()方法中抛出异常,然后重定向。