Search code examples
c#.net.net-coreaction-filtercustom-action-filter

ExceptionFilter doesn't run .NET Core Web Api


I have problem with Action Filters. None of my filters run. I am using .NET Core 2.2 and building Web Api. I registered it with [CustomExceptionFilter] in controller:

[HttpDelete("{id}")]
[CustomExceptionFilter]
public IActionResult Delete(int id)
        {
                var piano = _repository.GetPianoById(id);
                if (piano == null) throw new Exception(); 
                _repository.Delete(id);
                return Ok();
        }

Here is my Exception filter:

using System.Web.Http.Filters;

public class CustomExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        HttpStatusCode status = HttpStatusCode.InternalServerError;
        String message = String.Empty;
        var exceptionType = actionExecutedContext.Exception.GetType();
        if (exceptionType == typeof(Exception))
        {
            message = "Incorrect ID.";
            status = HttpStatusCode.NotFound;
        }

        actionExecutedContext.Response = new HttpResponseMessage()
        {
            Content = new StringContent(message, System.Text.Encoding.UTF8, "text/plain"),
            StatusCode = status
    };
        base.OnException(actionExecutedContext);
}

What can be wrong?


Solution

  • I am not sure what is wrong with your example, but this is how I have done it.

    First the exception filter:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
    

    I then add the filter to the whole controller, not just an action, although that might work too--I have never tried it:

    [ServiceFilter(typeof(CustomExceptionFilterAttribute))]
    public class MyController : ControllerBase
    {
    

    And in Startup.cs, ConfigureServices, add DI support:

    services.AddScoped<CustomExceptionFilterAttribute>();
    

    This blog goes into more detail.