简体   繁体   中英

Web API handle 404 if route not match

I'm working on Web API 2. For now my route table is

public void RegisterRoute(HttpRouteCollection routes) {
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

That works fine for urls:

http://localhost/api/user
http://localhost/api/user/4

When I specify not existing controller name ( http://localhost/api/abcd ) then result is JSON

{"message":"No HTTP resource was found that matches the request URI 'http://loocalhost/api/abc'."}

I need to return the same result for urls:

http://localhost/api/abc/abc/abc/abc
http://localhost/abc/abc/abc/abc
http://localhost/a

Now I have

在此处输入图片说明

How can I return JSON with 404 code for all unmatched routes?

Note: Some of action like http://localhost/api/user/4 also can returns 404 with some data in body. So, I need to have possibility handle 404 from action and 404 if route not match.

Please suggest. I've tried this

<httpErrors errorMode="Custom" existingResponse="Replace">
            <remove statusCode="404" />
            <error statusCode="404" responseMode="ExecuteURL" path="/Error/Missing" />
 </httpErrors>

But then action that returns 404 also redirects to /Error/Missing

U need to set your defaults for this, Currently only ID field is being treated as default not your controller. update your default route like this

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM