简体   繁体   中英

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.

在此输入图像描述

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

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