如何处理WebApi错误404 [英] How to handle WebApi error 404

查看:1196
本文介绍了如何处理WebApi错误404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在同一域中用WebApi2实现MVC 5应用程序. 我现在的问题是如何处理WebApi中的错误404.我在WebApi中使用路由.

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

现在我有了返回值字符串的URL "/myapi/value".问题是我请求"/myapi/value/bla/bla"或我的API中没有的任何URL,它返回错误404.

我尝试了以下链接 http://weblogs.asp.net/imranbaloch/handling-http-404-error-in-asp-net-web-api ,它仅适用于WebApi项目,不适用于MVC + WebApi项目.

请帮助. TIA

更新:

请仔细阅读!!!!

如果您不处理WebApi中的404,则这将是默认页面. 它包括您的身体路径.

解决方案

已更新:

我认为以下内容对如何为WebApi 2+项目实施错误处理有更好的描述:

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

这篇关于如何处理WebApi错误404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆