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

Asp.net core asp.net核心中NotFoundObjectResult的自定义页面,asp.net-core,asp.net-core-mvc,Asp.net Core,Asp.net Core Mvc,如何为NotFoundObjectResult创建自定义页面 实际上,当我返回这个结果时,应用程序只在页面中显示id return new NotFoundObjectResult(id); 每次获取NotFoundObjectResult时,我都需要重定向到“/errors/notfound”。您可以将app.useStatusCodePageSwithExecute或app.UseStatusCodePagesWithRedirect添加到管道(在app.UseMvc之前)。这将截获状态代

如何为NotFoundObjectResult创建自定义页面

实际上,当我返回这个结果时,应用程序只在页面中显示id

return new NotFoundObjectResult(id);

每次获取NotFoundObjectResult时,我都需要重定向到“/errors/notfound”。

您可以将
app.useStatusCodePageSwithExecute
app.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);