Web API 2.2 returns user 404 when resource (url) is not found

I want to be able to take the 404 response from the web api (iis) when the resource does not exist.

I did my research and came across only one solution that produced this work, but I'm not sure how safe this is, since "routeTemplate" is just {* url}

This message begs for help and explanation.

My application uses MVC and WebAPI ... will this pattern affect MVC? Is there any way to add "api" with {* url} in the template? (to make sure that only requests with "... / api / ..." are affected)

config.Routes.MapHttpRoute("Error404", "{*url}", new { controller = "Error", action = "Handle404" }); 

Can anyone find a cleaner way to do this and handle 404 in a web api?

EDIT 1

This code affects my MVC routes. How can I add "api" to "{* url}"? ... if I tried many different methods and did not play dice.

+9
c # asp.net-mvc asp.net-web-api asp.net-web-api-routing asp.net-web-api2
source share
1 answer

There was exactly the same problem. After some research, trial and error, I was able to find a working solution.

I have a RoutePrefix solution RoutePrefix and tried to implement something similar to how MVC controllers use HandleUnknownAction in the base controller.

With this post: Routing and inheriting .NET WebAPI attributes to ensure route inheritance, I created a base controller for my web APIs using the HandleUnknownAction method for example:

 public abstract class WebApiControllerBase : ApiController { [Route("{*actionName}")] [AcceptVerbs("GET", "POST", "PUT", "DELETE")]//Include what ever methods you want to handle [AllowAnonymous]//So I can use it on authenticated controllers [ApiExplorerSettings(IgnoreApi = true)]//To hide this method from helpers public virtual HttpResponseMessage HandleUnknownAction(string actionName) { var status = HttpStatusCode.NotFound; //This is custom code to create my response content //.... var message = status.ToString().FormatCamelCase(); var content = DependencyService .Get<IResponseEnvelopeFactory>() .CreateWithOnlyMetadata(status, message); //.... return Request.CreateResponse(status, content); } } 

If you do not want to follow the path of inheritance, you can always put the method directly in the controller to which you want to apply functionality.

This allows me to use route prefixes that process user-found messages that are specific to certain controllers, since I have both a back office and public, public APIs.

If the URL is not ApiController , the default error controller will handle those not found as usual.

+7
source share

All Articles