可以使用HttpException
return new HttpException(404, "Some description");
///////////// ADDED
您可以使用下面
代码的Web.config
<customErrors mode="On" defaultRedirect="~/Error">
</customErrors>
控制器:
public class ErrorController : Controller
{
public ViewResult Index(string message)
{
ViewBag.ErrorMessage = message;
return View("Error");
}
}
查看
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Error";
string errorMessage = (!string.IsNullOrEmpty(ViewBag.ErrorMessage))? ViewBag.ErrorMessage : " An unexpected error has occurred. Please contact the system administrator.";
}
<div class="row">
<span>Error</span>
</div>
<div class="row">
<div class="alert alert-error">
@errorMessage
</div>
</div>
代码:
var errorMessage = "";
if (id == null)
{
errorMessage = "Error Id";
}
//// do something ...
if (entity == null)
{
errorMessage = "Null Entity";
}
//// do something ...
if (somethingError())
{
errorMessage = "Something Error";
}
if (!string.IsNullOrEmpty(errorMessage)) return RedirectToAction("Index", "Error", new { message = errorMessage });
韩国社交协会的答案,但HttpException是不是一个ActionResult的 –
我可以看看你的404页面的代码,请。 – Zergling
我的回应很抱歉这么晚了,我 404页只是一个静态页面, 我设置httpErrors在我的web.config。 当一个404错误发生, 应该重定向到404页。 –