Introduction:
Building modern HTTP/RESTful/RPC
services has become very easy with the new ASP.NET Web API framework.
Using ASP.NET Web API framework, you can create HTTP services which can
be accessed from browsers, machines, mobile devices and other
clients. Developing HTTP services is now become more easy for ASP.NET
MVC developer becasue ASP.NET Web API is now included in ASP.NET MVC. In
addition to developing HTTP services, it is also important to return
meaningful response to client if a resource(uri) not found(HTTP 404) for
a reason(for example, mistyped resource uri). It is also important to
make this response centralized so you can configure all of 'HTTP 404 Not
Found' resource at one place. In this article, I will show you how
to handle 'HTTP 404 Not Found' at one place.
Description:
Let's say that you are developing
a HTTP RESTful application using ASP.NET Web API framework. In this
application you need to handle HTTP 404 errors in a centralized
location. From ASP.NET Web API point of you, you need to handle these
situations,
- No route matched.
- Route is matched but no {controller} has been found on route.
- No type with {controller} name has been found.
- No matching action method found in the selected controller due to no
action method start with the request HTTP method verb or no action
method with IActionHttpMethodProviderRoute implemented attribute found
or no method with {action} name found or no method with the matching
{action} name found.
Now, let create a ErrorController with Handle404
action method. This action method will be used in all of the above
cases for sending HTTP 404 response message to the client.
01 |
public class ErrorController : ApiController |
03 |
[HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions, AcceptVerbs( "PATCH" )] |
04 |
public HttpResponseMessage Handle404() |
06 |
var responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound); |
07 |
responseMessage.ReasonPhrase = "The requested resource is not found" ; |
08 |
return responseMessage; |
You can easily change the above
action method to send some other specific HTTP 404 error response. If a
client of your HTTP service send a request to a resource(uri) and no
route matched with this uri on server then you can route the request to
the above Handle404 method using a custom route. Put this route at the
very bottom of route configuration,
3 |
routeTemplate: "{*url}" , |
4 |
defaults: new { controller = "Error" , action = "Handle404" } |
Now you need handle the case when there is no
{controller} in the matching route or when there is no type with
{controller} name found. You can easily handle this case and route the
request to the above Handle404 method using a custom
IHttpControllerSelector. Here is the definition of a custom
IHttpControllerSelector,
01 |
public class HttpNotFoundAwareDefaultHttpControllerSelector : DefaultHttpControllerSelector |
03 |
public HttpNotFoundAwareDefaultHttpControllerSelector(HttpConfiguration configuration) |
07 |
public override HttpControllerDescriptor SelectController(HttpRequestMessage request) |
09 |
HttpControllerDescriptor decriptor = null ; |
12 |
decriptor = base .SelectController(request); |
14 |
catch (HttpResponseException ex) |
16 |
var code = ex.Response.StatusCode; |
17 |
if (code != HttpStatusCode.NotFound) |
19 |
var routeValues = request.GetRouteData().Values; |
20 |
routeValues[ "controller" ] = "Error" ; |
21 |
routeValues[ "action" ] = "Handle404" ; |
22 |
decriptor = base .SelectController(request); |
Next, it is also required to pass the request to
the above Handle404 method if no matching action method found in the
selected controller due to the reason discussed above. This situation
can also be easily handled through a custom IHttpActionSelector. Here is
the source of custom IHttpActionSelector,
01 |
public class HttpNotFoundAwareControllerActionSelector : ApiControllerActionSelector |
03 |
public HttpNotFoundAwareControllerActionSelector() |
07 |
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext) |
09 |
HttpActionDescriptor decriptor = null ; |
12 |
decriptor = base .SelectAction(controllerContext); |
14 |
catch (HttpResponseException ex) |
16 |
var code = ex.Response.StatusCode; |
17 |
if (code != HttpStatusCode.NotFound && code != HttpStatusCode.MethodNotAllowed) |
19 |
var routeData = controllerContext.RouteData; |
20 |
routeData.Values[ "action" ] = "Handle404" ; |
21 |
IHttpController httpController = new ErrorController(); |
22 |
controllerContext.Controller = httpController; |
23 |
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "Error" , httpController.GetType()); |
24 |
decriptor = base .SelectAction(controllerContext); |
Finally, we need to register the custom
IHttpControllerSelector and IHttpActionSelector. Open global.asax.cs
file and add these lines,
1 |
configuration.Services.Replace( typeof (IHttpControllerSelector), new HttpNotFoundAwareDefaultHttpControllerSelector(configuration)); |
2 |
configuration.Services.Replace( typeof (IHttpActionSelector), new HttpNotFoundAwareControllerActionSelector()); |
Summary:
In addition to building an
application for HTTP services, it is also important to send
meaningful centralized information in response when something goes
wrong, for example 'HTTP 404 Not Found' error. In this article, I
showed you how to handle 'HTTP 404 Not Found' error in a centralized
location. Hopefully you will enjoy this article too.
- Global Error Handling in ASP.NET Web API 2(webapi2 中的全局异常处理)
目前,在Web API中没有简单的方法来记录或处理全局异常(webapi1中).一些未处理的异常可以通过exception filters进行处理,但是有许多情况exception filters无法 ...
- Exception Handling in ASP.NET Web API webapi异常处理
原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...
- Exception Handling in ASP.NET Web API
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErr ...
- Asp.net web api部署在某些服务器上老是404
asp.net web api部署在Windows服务器上后,按照WebAPI定义的路由访问,老是出现404,但定义一个静态文件从站点访问,却又OK. 这时,便可以确定是WebAPI路由出了问题,经调 ...
- "Asp.Net Web Api MediaTypeFormatter Error for x-www-formurlencoded data" 解决方法
遇到标题中所说的问题原因是使用 jQuery AJAX 以 POST 方式调用 Asp.Net Web API .解决办法请看以下代码中有注释的部分. public static class WebA ...
- 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理
原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...
- Professional C# 6 and .NET Core 1.0 - Chapter 42 ASP.NET Web API
本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处: -------------------------------------------------------- ...
- 初试ASP.NET Web API/MVC API(附Demo)
写在前面 HTTP RESTful 创建Web API 调用Web API 运行截图及Demo下载 ASP.NET Web API是一个框架,可以很容易构建达成了广泛的HTTP服务客户端,包括浏览 ...
- ASP.NET Web API 异常日志记录
如果在 ASP.NET MVC 应用程序中记录异常信息,我们只需要在 Global.asax 的 Application_Error 中添加代码就可以了,比如: public class MvcApp ...
随机推荐
- java retention注解
Retention注解 Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源 ...
- TCL语言笔记:TCL中的控制结构命令
一.引言 控制结构允许程序根据不同的状态.条件和参数来选择不同的处理和执行路径,从而使代码具有更强的灵活性.健壮性和可读性. Tcl 提供了 if.if/else.if/elseif.foreach. ...
- Lambda 表达式型的排序法
int[] arry = {3,9,5,7,64,51,35,94 }; foreach (int i in arry.OrderBy(i => i)) Console.WriteLine(i) ...
- SQLServer中服务器角色和数据库角色权限详解
角色 当几个用户需要在某个特定的数据库中执行类似的动作时(这里没有相应的Windows用户组),就可以向该数据库中添加一个角色(role).数据库角色指定了可以访问相同数据库对象的一组数据库用户. 数 ...
- jQuery--隐藏事件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- TCP建立连接和释放的过程,及TCP状态变迁图
一.TCP报文格式 下面是TCP报文格式图: 重要字段介绍: (1)序号:Seq序号,占32位,用来标识从TCP源端向目的端发送的字节流,发起方发送数据时对此进行标记. (2)确认序号:Ack序号,占 ...
- 1223. Chernobyl’ Eagle on a Roof(dp)&&poj3783
经典DP n个鹰蛋 m层楼 刚开始是二分想法 不过当数小于二分的那个值 貌似没发判断 dp[i][j] = min(dp[i][j],max(dp[i-1][k-1],dp[i][j-k]) 选择第k ...
- launch genymotion simulator from command line
Command to launch genymotion headless - player --vm-name Nexus_4 if player is not already added to p ...
- tornado中使用torndb,连接数过高的问题
问题背景 最近新的产品开发中,使用了到了Tornado和mysql数据库.但在基本框架完成之后,我在开发时候发现了一个很奇怪的现象,我在测试时,发现数据库返回不了结果,于是我在mysql中输入show ...
- 关于Hibernate中的Configuration
Hibernate中,关于从 Configuration中建立一个SessionFactory常用的可以有两种方法,一种是为Configuration提供hibernate.cfg.xml配置文件,还 ...