当前位置: 首页 > 编程语言 > C#

Customerrorpagefornon-existingdirectory-fileWebAPI(notacontroller)分享

时间:2023-04-10 14:45:20 C#

不存在的页面现有控制器或错误的路由设置自定义错误页面但如果用户尝试在某个不存在的目录中下载文件,我如何显示自定义错误页面?我根本无法工作。它仍然显示默认错误页面。这篇博文将指导您处理ASP.NetWebAPI中的404错误:http://weblogs.asp.net/imranbaloch/handling-http-404-error-in-asp-net-web-api假设您使用的是ASP.NETWebAPI框架来开发HTTPRESTful应用程序。在此应用程序中,您需要在一个集中位置处理HTTP404错误。从ASP.NETWebAPI的角度来看,您需要处理这些情况,现在,让我们创建一个带有Handle404操作方法的ErrorController。此操作方法将在上述所有情况下用于向客户端发送HTTP404响应消息。公共类ErrorController:ApiController{[HttpGet,HttpPost,HttpPut,HttpDelete,HttpHead,HttpOptions,AcceptVerbs("PATCH")]publicHttpResponseMessageHandle404(){varresponseMessage=newHttpResponseMessage(HttpStatusCode.NotFound);responseMessage.ReasonPhrase="没有找到请求的资源";返回响应消息;您可以轻松更改上述操作方法以发送一些其他特定的HTTP404错误响应。如果一个HTTP服务的客户端向一个资源(uri)发送请求,而服务器上没有匹配这个uri的路由,可以使用自定义路由将请求路由到上面的Handle404方法。将此路由放在路由配置的最底部,routes.MapHttpRoute(name:"Error404",routeTemplate:"{*url}",defaults:new{controller="Error",action="Handle404"});现在,您需要处理匹配路由中没有{controller}或找不到{controller}名称类型的情况。您可以轻松处理这种情况并使用自定义IHttpControllerSelector将请求路由到上面的Handle404方法。这是自定义IHttpControllerSelector的自定义,publicclassHttpNotFoundAwareDefaultHttpControllerSelector:DefaultHttpControllerSelector{publicHttpNotFoundAwareDefaultHttpControllerSelector(HttpConfigurationconfiguration):base(configuration){}publicoverrideHttpControllerDescriptorSelectController(HttpNotFoundAwareDefaultHttpControllerSelector)尝试{decriptor=base.SelectController(request);}catch(HttpResponseExceptionex){varcode=ex.Response.StatusCode;如果(代码!=HttpStatusCode.NotFound)抛出;varrouteValues=request.GetRouteData().Values;routeValues["controller"]="Error";routeValues["action"]="Handle404";descriptor=base.SelectController(请求);}返回描述符;接下来,如果由于上述原因,在选中的控制器中没有找到匹配的action方法,那么也需要将request传递给上面的Handle404方法。这种情况也可以使用自定义IHttpActionSelector轻松处理。这是自定义IHttpActionSelector的源代码,尝试{descriptor=base.SelectAction(controllerContext);}catch(HttpResponseExceptionex){varcode=ex.Response.StatusCode;如果(代码!=HttpStatusCode.NotFound&&代码!=HttpStatusCode.MethodNotAllowed)抛出;varrouteData=controllerContext.RouteData;routeData.Values["action"]="Handle404";IHttpControllerhttpController=newErrorController();controllerContext.Controller=httpController;controllerContext.ControllerDescriptor=newHttpControllerDescriptor(controllerContext.Configuration,"Error",httpController.GetType());描述符=base.SelectAction(controllerContext);}返回描述符;}}最后,我们需要注册自定义IHttpControllerSelector和IHttpActionSelector打开global.asax.cs文件,添加这几行,以上是C#学习教程:不存在的目录/文件WebAPI(notcontroller)自定义错误页面分享全部内容,如果对大家有用并且需要了解更多C#学习教程,希望大家多多关注——configuration.Services.Replace(typeof(IHttpControllerSelector),newHttpNotFoundAwareDefaultHttpControllerSelector(configuration));configuration.Services.Replace(typeof(IHttpActionSelector),newHttpNotFoundAwareController(Action)Selector);本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: