当前位置: 首页> 文旅> 旅游 > ASP.NET Core 入门教学六 异常设置

ASP.NET Core 入门教学六 异常设置

时间:2025/7/9 1:05:15来源:https://blog.csdn.net/masonwu21/article/details/141832580 浏览次数:0次

在ASP.NET Core中,异常处理是一个重要的部分,可以帮助我们捕获和处理应用程序中的错误。以下是如何在ASP.NET Core中设置异常处理的步骤:

1. 全局异常处理中间件

ASP.NET Core提供了一个中间件来捕获未处理的异常。你可以在Startup.cs文件中配置这个中间件。

 
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");});
}

在这个例子中,app.UseExceptionHandler("/Home/Error")指定了当发生未处理的异常时,用户将被重定向到/Home/Error路径。

2. 自定义错误页面

你可以创建一个自定义的错误页面来显示错误信息。首先,创建一个Error.cshtml视图文件:

 
@model ErrorViewModel<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>@if (Model.ShowRequestId)
{<p><strong>Request ID:</strong> 在ASP.NET Core中,异常处理是一个重要的部分,可以帮助我们捕获和处理应用程序中的错误。以下是如何在ASP.NET Core中设置异常处理的步骤:### 1. 全局异常处理中间件ASP.NET Core提供了一个中间件来捕获未处理的异常。你可以在`Startup.cs`文件中配置这个中间件。```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");});
}

在这个例子中,app.UseExceptionHandler("/Home/Error")指定了当发生未处理的异常时,用户将被重定向到/Home/Error路径。

2. 自定义错误页面

你可以创建一个自定义的错误页面来显示错误信息。首先,创建一个Error.cshtml视图文件:

 
@model ErrorViewModel<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>@if (Model.ShowRequestId)
{<p><strong>Request ID:</strong> <code>@Model.RequestId</code></p>
}<p><strong>Exception:</strong> @Model.Exception.Message
</p>

然后,在HomeController中添加一个Error动作方法:

 
public class HomeController : Controller
{public IActionResult Index(){return View();}public IActionResult Error(){var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();var exception = exceptionHandlerPathFeature?.Error;var statusCode = StatusCodes.Status500InternalServerError; // 默认为500// 根据异常类型设置状态码if (exception is FileNotFoundException){statusCode = StatusCodes.Status404NotFound;}var errorViewModel = new ErrorViewModel{RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier,Exception = exception,StatusCode = statusCode};return View(errorViewModel);}
}

3. 使用IExceptionHandler接口

如果你需要更复杂的异常处理逻辑,可以实现IExceptionHandler接口。首先,创建一个自定义的异常处理器:

 
public class CustomExceptionHandler : IExceptionHandler
{public void HandleException(Exception ex){// 在这里处理异常,例如记录日志、发送通知等}
}

然后,在Startup.cs中注册这个处理器:

 
public void ConfigureServices(IServiceCollection services)
{services.AddControllersWithViews();services.AddSingleton<IExceptionHandler, CustomExceptionHandler>();
}

4. 使用ExceptionFilterAttribute

你还可以创建一个自定义的异常过滤器来处理控制器中的异常。首先,创建一个自定义的异常过滤器:

 
public class CustomExceptionFilter : ExceptionFilterAttribute
{public override void OnException(ExceptionContext context){// 在这里处理异常,例如记录日志、发送通知等// 设置结果以阻止进一步的异常处理context.Result = new ViewResult{ViewName = "Error",ViewData = new ViewDataDictionary<ErrorViewModel>(context.Exception),TempData = context.Controller.TempData};context.ExceptionHandled = true;}
}

然后,在控制器或动作方法上应用这个过滤器:

 
[TypeFilter(typeof(CustomExceptionFilter))]
public class HomeController : Controller
{// ...
}

通过这些步骤,你可以在ASP.NET Core中设置全局和局部的异常处理,以便更好地捕获和处理应用程序中的错误。

关键字:ASP.NET Core 入门教学六 异常设置

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: