【问题标题】:Encapsulate WEB API Rest Result封装WEB API Rest Result
【发布时间】:2020-08-27 03:08:05
【问题描述】:

我正在构建一个 WEB API,它有很多这样的 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();
        }
    }

如何用可重复利用的代码封装这种行为?

【问题讨论】:

    标签: c# rest asp.net-web-api


    【解决方案1】:

    您可以通过创建 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));
    }
    

    【讨论】:

    • 感谢您的宝贵时间!
    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2020-01-16
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    相关资源
    最近更新 更多