我正在构建一个WEB,它有很多这样的GET方法:
[HttpGet]
[Authorize]
[Route("monedas")]
public IHttpActionResult GetMonedas(string empresaId, string filtro = "")
{
IEnumeradorService sectoresService = new MonedasService(empresaId);
if (!initialValidation.EmpresaPerteneceACliente(empresaId, User))
{
return Content(HttpStatusCode.MethodNotAllowed, "La empresa no existe o el cliente no tiene acceso a ella");
}
try
{
return Ok(sectoresService.Enumerar(filtro));
}
catch (QueryFormatException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
return InternalServerError();
}
}
[HttpGet]
[Authorize]
[Route("paises")]
public IHttpActionResult GetPaises(string empresaId, string filtro = "")
{
IEnumeradorService sectoresService = new PaisesService(empresaId);
if (!initialValidation.EmpresaPerteneceACliente(empresaId, User))
{
return Content(HttpStatusCode.MethodNotAllowed, "La empresa no existe o el cliente no tiene acceso a ella");
}
try
{
return Ok(sectoresService.Enumerar(filtro));
}
catch (QueryFormatException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
return InternalServerError();
}
}如何用可重用的代码封装这种行为?
发布于 2017-10-11 14:52:27
可以通过创建一个ExceptionFilterAttribute来删除所有try/catch语句
public class HandleExceptionsFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is QueryFormatException)
{
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception.Message);
return;
}
System.Diagnostics.Debug.WriteLine(context.Exception);
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}然后将其添加到应用程序中:
config.Filters.Add(new HandleExceptionsFilter());这将使您的行为看起来像这样:
[HttpGet]
[Authorize]
[Route("monedas")]
public IHttpActionResult GetMonedas(string empresaId, string filtro = "")
{
IEnumeradorService sectoresService = new MonedasService(empresaId);
if (!initialValidation.EmpresaPerteneceACliente(empresaId, User))
{
return Content(HttpStatusCode.MethodNotAllowed, "La empresa no existe o el cliente no tiene acceso a ella");
}
return Ok(sectoresService.Enumerar(filtro));
}
[HttpGet]
[Authorize]
[Route("paises")]
public IHttpActionResult GetPaises(string empresaId, string filtro = "")
{
IEnumeradorService sectoresService = new PaisesService(empresaId);
if (!initialValidation.EmpresaPerteneceACliente(empresaId, User))
{
return Content(HttpStatusCode.MethodNotAllowed, "La empresa no existe o el cliente no tiene acceso a ella");
}
return Ok(sectoresService.Enumerar(filtro));
}https://stackoverflow.com/questions/46656156
复制相似问题