public class LoggingFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext context) { var response = context.Response; var statusCode = response.StatusCode; var message = response.Content.ReadAsStringAsync().Result; // log response details to a log file or database } }
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { var ex = context.Exception; var message = ex.Message; // handle the exception and return a custom response var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(message), ReasonPhrase = "Internal Server Error" }; context.Response = response; } }In this example, a CustomExceptionFilterAttribute is defined that handles unhandled exceptions thrown by Web API actions. The OnException method is triggered when an exception occurs, giving access to the HttpActionExecutedContext. The example creates a custom response with a message that describes the error and sets it as the response for the context. This will be returned to the client as an HTTP 500 Internal Server Error response. Package library: System.Web.Http.