简体   繁体   中英

Override 404 Not found in Asp.Net core Web API

i wish to implement overriding of 404 not found in case of unsupported requests , and respond with a more helpful message to consumer.

I found this Link to ensure this in .net framework however the config override of this way is not supported in .Net core.

var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("rangeWithStatus", 
typeof(RangeWithStatusRouteConstraint));
config.MapHttpAttributeRoutes(constraintResolver);

Above code is content of WebApiConfig file which is no longer needed in asp.net core. What alternative should I do to use ?

For Web Api its normally cleaner and easier to use the middleware feature. You can basically wrap all of your requests in some code which will allow you to handle exceptions. An example of which can be found here:

https://blogs.msdn.microsoft.com/brandonh/2017/07/31/using-middleware-to-trap-exceptions-in-asp-net-core/

I use a similar thing to handle formatting the responses into a uniform structure as well as handling exceptions and outputting different text depending on the specific error

Asp.net Core Web API is provided with the multiple practices to handle exceptions. Middleware seems to be the best approach to handle it.
You can read the methodologies with examples on this article.

https://code-maze.com/global-error-handling-aspnetcore/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM