当.NET MVC返回HttpNotFound时,statusDescription在哪里

时间:2015-12-22 04:56:13

标签: .net asp.net-mvc http web

像这样的代码

if (id == null)
{
    return HttpNotFound("Error Id");
}
//// do something ...
if (entity == null)
{
    return HttpNotFound("Null Entity");
}
//// do something ...
if (somethingError())
{
    return HttpNotFound("Something Error");
}

如果我请求使用浏览器,

我将获得一张之前设置的404页面。

但是错误消息(statusDescription)在哪里?

我在Header或Raw上找不到它。

1 个答案:

答案 0 :(得分:1)

您可以使用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 });