asp.net核心中NotFoundObjectResult的自定义页面

时间:2016-09-24 09:10:34

标签: asp.net-core asp.net-core-mvc

如何为NotFoundObjectResult结果创建自定义页面?

实际上,当我返回此结果时,应用程序仅在页面中显示id。

return new NotFoundObjectResult(id);

我需要重定向到" / errors / notfound"每次得到NotFoundObjectResult。

1 个答案:

答案 0 :(得分:1)

您可以将app.UseStatusCodePagesWithReExecuteapp.UseStatusCodePagesWithRedirect添加到管道(app.UseMvc之前)。这将截取状态代码介于400和600之间的任何响应还没有正文

在你的启动课程中:

app.UseStatusCodePagesWithReExecute("/statuscode/{0}");

然后添加一个新的控制器:

public class HttpStatusController: Controller
{
    [HttpGet("statuscode/{code}")]
    public IActionResult Index(HttpStatusCode code)
    {
        return View(code);
    }
}

并添加一个视图Views / HttpStatus / Index.cshtml:

@model System.Net.HttpStatusCode
@{
    ViewData["Title"] = "Error " + (int)Model;
}

<div class="jumbotron">
    <h1>Error @((int)Model)!</h1>
    <p><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></p>
</div>

现在您只需要从控制器返回所需的状态代码,而无需添加任何可选的正文:

//These would end up in the new HttpStatus controller, they just specify the status code
return StatusCode(404);
return new StatusCodeResult(404);

//Any of these won't, as they add either the id or an object to the response's body
return StatusCode(404, 123);
return StatusCode(404, new { id = 123 });
return new NotFoundObjectResult(123);