简体   繁体   English

封装WEB API Rest结果

[英]Encapsulate WEB API Rest Result

I'm building a WEB API, which has many GET methods like these:我正在构建一个 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();
        }
    }

How can I encapsulate this kind of behavior with re-utilizable code?我怎样才能用可重用的代码封装这种行为?

You can remove all the try/catch statements by creating an ExceptionFilterAttribute :您可以通过创建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);
    }
}

Then add it to your application:然后将其添加到您的应用程序中:

config.Filters.Add(new HandleExceptionsFilter());

This will make your actions look like this:这将使您的操作如下所示:

[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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM