C# 以更好的方式使用 db 上下文和异常处理 (DRY)
本文关键字:异常处理 DRY 上下文 db 更好 方式使 | 更新日期: 2023-09-27 18:35:29
我在 Web API 控制器中的所有操作方法中以 WEP API 控制器的给定操作编写这段代码,导致大量代码冗余并重复我自己(!DRY)因此,我需要一种方法,可以使用继承或迭代面或使用任何其他面向对象的方法,通过更好的方法来完成此操作。
[Route("myApiGetRequest")]
[HttpGet]
public IHttpActionResult myApiGetRequest(long id)
{
try
{
DataTable transaction = new DataTable();
using (var context = new myDbContext())
{
//code for what I want to do
}
}
catch (Exception ex)
{
return Ok(new { success = false, message = ex.Message });
}
}
您可以利用 WebApi
中提供的异常过滤器。然后,将异常处理代码移动到该筛选器。
例如:
public class MyExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is Exception)
{
context.Response = new HttpResponseMessage { Content = new StringContent("Exception occured", System.Text.Encoding.UTF8, "text/plain"), StatusCode = HttpStatusCode.InternalServerError};
}
}
}
然后在WebApi
控制器中,您可以执行以下操作:
[Route("myApiGetRequest")]
[HttpGet]
[MyExceptionFilter]
public IHttpActionResult myApiGetRequest(long id)
{
DataTable transaction = new DataTable();
using (var context = new myDbContext())
{
//code for what I want to do
}
}
然后myApiGetRequest
中发生的异常将由此方法修饰的相应异常过滤器处理
ExceptionHandling 可以通过实现自己的 ExceptionFilterAttribute
来完成。可以使用此属性来修饰所有需要异常处理的控制器。
基本上,您重写 OnException
方法并将不同的异常类型转换为状态代码和消息。