0
Ich baue eine Web-API, Wich hat viele GET-Methoden wie diese:Encapsulate WEB API Übriges Ergebnis
Die Frage ist: Wie kann ich diese Art von Verhalten mit Wieder nutzbaren Code kapseln?
Danke!
Ich baue eine Web-API, Wich hat viele GET-Methoden wie diese:Encapsulate WEB API Übriges Ergebnis
Die Frage ist: Wie kann ich diese Art von Verhalten mit Wieder nutzbaren Code kapseln?
Danke!
können Sie entfernen Sie alle try/catch-Anweisungen durch die Schaffung eines ExceptionFilterAttribute
:
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);
}
}
Dann fügen Sie es Ihrer Anwendung:
config.Filters.Add(new HandleExceptionsFilter());
Dies wird Ihre Aktionen wie folgt aussehen:
[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));
}
Vielen Dank für Ihre Zeit! – ericpap