2013-05-08 4 views
8

Gibt es in der ASP.NET-Web-API eine Möglichkeit, eine Ausnahme als in einem ExceptionFilterAttribute behandelt zu markieren?In der Web-API festgelegte Ausnahmeeinstellung ExceptionFilterAttribute

Ich möchte die Ausnahme auf Methodenebene mit einem Ausnahmefilter behandeln und die Weitergabe an einen global registrierten Ausnahmefilter stoppen.

Filter auf eine Controller-Aktion verwendet:

public class MethodExceptionFilterAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext context) 
    { 
     if (context.Exception is NotImplementedException) 
     { 
      context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError) 
      { 
       Content = new StringContent(context.Exception.Message) 
      }; 
      // here in MVC you could set context.ExceptionHandled = true; 
     } 
    } 
} 

Der global registriert Filter:

public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext context) 
    { 
     if (context.Exception is SomeOtherException) 
     { 
      context.Response = new HttpResponseMessage(HttpStatusCode.SomethingElse) 
      { 
       Content = new StringContent(context.Exception.Message) 
      }; 
     } 
    } 
} 
+0

Können Sie bitte ein Beispiel Ihrer "behandeln die Ausnahme auf der Methodenebene mit einem Ausnahmefilter"? – giacomelli

+0

Um zu dem globalen Filter zu gelangen, muss die Ausnahme in der Methode an erster Stelle behandelt werden, denke ich - also warum nicht den unsicheren Code in einen "try/catch" Block schreiben und dort behandeln? –

+0

Beispiele hinzugefügt. – adamwtiko

Antwort

2

Versuchen Sie, eine HttpResponseException am Ende Ihrer lokalen Handhabung zu werfen. Sie werden von Ausnahmefiltern nicht berücksichtigt.

throw new HttpResponseException(context.Response); 
+0

Alte Antwort, aber ich wollte nur darauf hinweisen, dass es nicht verhindert, dass mehr Handhabung gemacht wird. – Tipx

Verwandte Themen