asp.net-core - asp.net core 中 NotFoundObjectResult 的自定义页面

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

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

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

return new NotFoundObjectResult(id);

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

最佳答案

您可以将 app.UseStatusCodePagesWithReExecuteapp.UseStatusCodePagesWithRedirect 添加到管道(在 app.UseMvc 之前)。这将拦截任何状态代码在 400 到 600 之间且尚无正文的响应。

在您的 Startup 类中:

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

然后添加一个新的 Controller :

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

并添加一个 View 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>

现在您只需从 Controller 返回所需的状态代码,无需添加任何可选主体:

//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);

关于asp.net-core - asp.net core 中 NotFoundObjectResult 的自定义页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674609/

相关文章:

javascript - 我们是否需要 NodeJs 来在服务器上运行 react 应用程序?

c# - 设置 Asp.Net Core MVC Json 选项

ajax - Ajax 刷新的 ViewComponent 替代方案

asp.net-core - 返回404页面,无需重定向

c# - 使用 ASP.NET Core API 返回 View

asp.net - 使用 ASP.NET Core Web Api 验证第 3 方 Cookie

asp.net-core - 在 ASP.NET Core 中存储生产 secret

c# - 通过依赖注入(inject)获取连接字符串

c# - 具有不同 Controller 但相同操作名称的路由无法生成所需的 url

asp.net - 在 Visual Studio 构建中恢复 Bower 组件