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)
};
}
}
}
Können Sie bitte ein Beispiel Ihrer "behandeln die Ausnahme auf der Methodenebene mit einem Ausnahmefilter"? – giacomelli
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? –
Beispiele hinzugefügt. – adamwtiko