c# - 属性路由不是现有路由
问题描述
我有一个带有属性路由的项目,例如:
[Route("home")]
public class HomeController : Controller
{
[HttpPost]
public IActionResult Post(int id)
{
}
[HttpGet]
public IActionResult Get()
{
}
}
现在我想捕获所有没有指定路由的 Get/Post/Put 请求。所以我可以返回一个错误,重定向到主页等等。是否可以使用 AttributeRouting 或者我应该在启动时使用常规路由?“不存在”的路线在那里看起来如何?
解决方案
默认情况下,服务器返回 404 HTTP 状态代码作为对未由任何中间件处理的请求的响应(属性/约定路由是 MVC 中间件的一部分)。
一般来说,你总是可以做的是在管道的开头添加一些中间件来捕获所有带有 404 状态代码的响应并执行自定义逻辑或更改响应。
在实践中,您可以使用 ASP.NET Core 提供的称为StatusCodePages
中间件的现有机制。您可以通过以下方式将其直接注册为原始中间件
public void Configure(IApplicationBuilder app)
{
app.UseStatusCodePages(async context =>
{
context.HttpContext.Response.ContentType = "text/plain";
await context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
//note that order of middlewares is importante
//and above should be registered as one of the first middleware and before app.UseMVC()
中间件支持几种扩展方法,如下所示(区别在本文中有很好的解释):
app.UseStatusCodePages("/error/{0}");
app.UseStatusCodePagesWithRedirects("/error/{0}");
app.UseStatusCodePagesWithReExecute("/error/{0}");
where"/error/{0}"
是一个路由模板,可以是你需要的任何东西,它的{0}
参数将代表错误代码。
例如,要处理 404 错误,您可以添加以下操作
[Route("error/404")]
public IActionResult Error404()
{
// do here what you need
// return custom API response / View;
}
或一般行动
[Route("error/{code:int}")]
public IActionResult Error(int code)
推荐阅读
- excel - 使用 ARRAY 函数返回基于新月份的数值。当 false 希望值来自基于日期的另一列数字时
- python - 如何通过多个发布请求正确启动我的蜘蛛以从其响应中抓取内容?
- html - 如何通过引导程序在项目显示弹性盒设计下删除多余的空间
- android - 关闭应用程序时是否可以接收广播
- javascript - 如何使用代码镜像中的数据对象更改值
- postgresql - TypeORM 命名连接抛出“未找到连接默认值”
- android - 如何使用firebase auth获取谷歌访问令牌
- python - 线程目标函数未完成
- reactjs - 如何将 React 组件中的值插入到 textarea 值中
- python - 弹性搜索不返回结果 python