How to catch undefined api method calls in ASP.NET MVC4 Web API

前端 未结 1 609
暗喜
暗喜 2021-01-18 12:16

ASP.NET / Mono MVC4 Web API v.1 application.

How to catch calls to undefined api methods. Calling http://localhost:52216/erp/api/undefinedmethod returns

1条回答
  •  借酒劲吻你
    2021-01-18 12:36

    Imran Baloch wrote an article on exactly how to achieve this. Basically you need to create your own HttpControllerSelector and HttpActionSelector. You can find the article here.

    EDIT:

    If your application uses routes other than those registered in the WebApiConfig you will need to make some changes to the routing. Instead of defining the Error404 route at the end of the Register method, define a new method (RegisterNotFound) to register the route:

    public static class WebApiConfig
    {    
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    
        public static void RegisterNotFound(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "Error404",
                routeTemplate: "{*url}",
                defaults: new { controller = "Error", action = "Handle404" }
            );
        }
    }
    

    And then in the Global.asax register call this method last:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        WebApiConfig.RegisterNotFound(GlobalConfiguration.Configuration);
    
    
        GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), 
            new HttpNotFoundAwareDefaultHttpControllerSelector(GlobalConfiguration.Configuration));
        GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionSelector), 
            new HttpNotFoundAwareControllerActionSelector());
    
    }
    

    0 讨论(0)
提交回复
热议问题