自定义ApiControllerActionSelector,重写SelectAction方法,调用base.SelectAction(),并捕获HttpResponseException,判断HttpStatusCode值是否是404,最后应用该Selector
你好,前两天看到你的回复了。但是我也是刚做接口,有些不太明白Webapi的一些问题。例如怎么捕获HttpResponseException,判断HttpStatusCode值是否是404等。麻烦你能用一段简单的代码演示一下吗?
@AzureSky:
1.自定义IHttpActionSelector
public class NotFoundHttpActionSelector : ApiControllerActionSelector { public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext) { HttpActionDescriptor descriptor = null; try { descriptor = base.SelectAction(controllerContext); } catch (HttpResponseException ex) { var statusCode = ex.Response.StatusCode; if (statusCode != HttpStatusCode.NotFound && statusCode != HttpStatusCode.MethodNotAllowed) throw; //这里可以转到错误处理的Action } return descriptor; } }
2.在Application_Start中注册
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); var config = GlobalConfiguration.Configuration; config.Services.Replace(typeof(IHttpActionSelector), new NotFoundHttpActionSelector()); }
@jello chen: 思路不错,谢谢。
@jello chen: 准备试下