在ASP.NET Core中,可以使用中间件来处理异常。以下是一个处理异常的示例代码:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// 配置其他服务
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
// 配置其他中间件
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
在上述代码中,我们首先检查当前的环境是否是开发环境。如果是开发环境,我们使用UseDeveloperExceptionPage
中间件来显示详细的异常信息。如果不是开发环境,我们使用UseExceptionHandler
中间件来处理异常,并将用户重定向到/Home/Error
页面。
在UseExceptionHandler
中间件中,您可以自定义异常处理程序,例如:
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var exceptionHandlerPathFeature = context.Features.Get();
var exception = exceptionHandlerPathFeature.Error;
await context.Response.WriteAsync($"Error: {exception.Message}
").ConfigureAwait(false);
});
});
在上述代码中,我们使用IExceptionHandlerPathFeature
来获取引发异常的路径和异常对象。您可以根据需要自定义异常处理逻辑。
请确保在ConfigureServices
方法中注册所需的服务和中间件。例如,您需要在ConfigureServices
方法中添加以下代码来启用MVC:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
这样,您就可以在ASP.NET Core中处理异常了。如果异常处理仍然不起作用,请检查代码中的其他配置和逻辑,以确保没有其他中间件或过滤器干扰异常处理。