在ASP.NET Core 2中,你可以使用中间件来处理HTTP 4xx错误。下面是一个示例代码,演示了如何使用ASP.NET Core 2中的中间件来处理HTTP 4xx错误:
首先,在Startup.cs文件的Configure方法中,将以下代码添加到中间件管道中:
app.UseStatusCodePages(async context =>
{
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.NotFound)
{
response.Redirect("/error/404");
}
else if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
response.Redirect("/error/401");
}
// 添加其他的HTTP 4xx错误处理逻辑
// 设置响应内容的类型
response.ContentType = "text/plain";
await response.WriteAsync($"Status code page: {response.StatusCode}");
});
接下来,你需要创建一个ErrorController来处理这些HTTP 4xx错误。在Controllers文件夹中,创建一个名为ErrorController.cs的文件,并将以下代码添加到该文件中:
using Microsoft.AspNetCore.Mvc;
namespace YourAppName.Controllers
{
public class ErrorController : Controller
{
[Route("error/404")]
public IActionResult PageNotFound()
{
return Content("Page not found");
}
[Route("error/401")]
public IActionResult Unauthorized()
{
return Content("Unauthorized");
}
}
}
在这里,我们为每个HTTP 4xx错误创建了一个相应的动作方法,并返回适当的响应内容。
最后,在Startup.cs文件的Configure方法中,将以下代码添加到中间件管道中,以将路由映射到ErrorController:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "error",
template: "{controller=Error}/{action=PageNotFound}/{id?}");
});
这样,当发生HTTP 4xx错误时,中间件会将请求重定向到相应的ErrorController动作方法,并返回适当的响应内容。
请根据你的实际需求,修改和添加中间件和控制器动作方法来处理其他HTTP 4xx错误。