0

I am looking for option to override default 404 not found Route error in Web API and found this link Override Route

As per the description, I could create class like below

   public class HttpNotFoundAwareController:ApiControllerActionSelector
{

    public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
    {
        HttpActionDescriptor descriptor = null;
        try
        { 
        descriptor= base.SelectAction(controllerContext);
        }
        catch(HttpResponseException ex)
        {
            var code = ex.Response.StatusCode;
        }

        return descriptor;
    }
}

However, this overriding needs to also be registered. From the link it shall be done in WebAPIConfig as below

configuration.Services.Replace(typeof(IHttpControllerSelector), new HttpNotFoundAwareDefaultHttpControllerSelector(configuration));

However I am not sure, how I could register the overriding in .Net Core Startup.cs file? as there is no Replace attribute available for Services.

Can anybody help?

Mandar Jogalekar
  • 3,199
  • 7
  • 44
  • 85
  • `IHttpControllerSelector` is not available in ASP.NET Core: https://medium.com/go-ahead-tours-tech-blog/versioning-web-api-controllers-in-net-core-39cecf842359 – mm8 Aug 16 '19 at 13:22
  • This link might be useful in your scenario - https://stackoverflow.com/questions/43590769/replace-service-registration-in-asp-net-core-built-in-di-container – Aparna Gadgil Aug 16 '19 at 13:24

1 Answers1

0

For capturing 404 and return custom error, you could try UseStatusCodePages like

app.UseStatusCodePages(new StatusCodePagesOptions {
    HandleAsync = async context =>
    {
        if (context.HttpContext.Response.StatusCode == StatusCodes.Status404NotFound)
        {
            await context.HttpContext.Response.WriteAsync($"{context.HttpContext.Request.Path} is not Found");
        }
    }
});
Edward
  • 28,296
  • 11
  • 76
  • 121