2017-10-09 9 views
0

私はWEB APIを構築するよ、ウィッヒは、これらのような多くのGETメソッドを持っていますカプセル化のWEB APIレスト結果

質問です:どのように私は、再利用可能なコードと行動のこの種をカプセル化することができますか?

ありがとうございます!お使いのアプリケーションに追加する次に

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()); 

これは、あなたの行動は次のように見えるようになります:

答えて

1

あなたがExceptionFilterAttributeを作成することによって、すべてのtry/catchステートメントを削除することができます

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

ありがとう! – ericpap