Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle WebApi error 404

I'm implementing MVC 5 application with WebApi2 in a same domain. My problem now is how to handle error 404 in WebApi. I'm using routing in my WebApi.

[RoutePrefix("myapi")]
public class MyApiController : ApiController 
{
[Route("value")]
public string myvalue()
{
return "value";
}
}

Now I have my url "/myapi/value" that returns value string. The problem is I requested "/myapi/value/bla/bla" or any URL that is not in my API, it returns error 404.

I tried this link http://weblogs.asp.net/imranbaloch/handling-http-404-error-in-asp-net-web-api, it only applies in a WebApi project but not in a MVC + WebApi Project.

Please help. TIA

UPDATE:

Please read carefully!!!!

This will be the default page if you don't handle 404 in your WebApi. It includes here your physical path.

enter image description here

like image 832
dan Avatar asked Aug 03 '15 07:08

dan


1 Answers

Updated:

I think the following has a better description on how to implement error handling for a WebApi 2+ project: http://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling .

There are two problems I had in my projects when combining the MVC and WebApi in the same project.

The first being that my error handling of my normal MVC pages did not work anymore. To resolve this I initialized the WebApi routing first, over the MVC controller routing and made some small adjustments in the web.config like described in your post.

Secondly if you want to handle invalid webapi routings, for example the correct directory but with wrong values which can not be resolved. try the solution in the "Global error handling" section of the below link: http://weblogs.asp.net/jongalloway/looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-4-web-api-help-pages-bson-and-global-error-handling

like image 90
Kevin Hendricks Avatar answered Oct 07 '22 01:10

Kevin Hendricks