Web API cannot access 404

Source: Internet
Author: User

Recently, you need to add a Web Api to your project that is a. NET Mvc4 project. To add an API, no matter how you encapsulate it, you can simply register the WEBAPI route in the Application_Start method. For example, the following code:

public static class Webapiconfig    {public        static void Register (httpconfiguration config)        {            config. Routes.maphttproute (                name: "Defaultapi",                routetemplate: "Api/{controller}/{id}",                defaults:new {id = Routeparameter.optional}            );        }    }

Calling the above register method in the Application_Start method is equivalent to registering the completion. But the author has completed the above work, access to the API is 404 error, can not find. The solution is not good.

Finally, the registration order of the original route is found to be related. A normal MVC project registers the routing information for normal controller,action: for example, the following code:

public static void RegisterRoutes (RouteCollection routes)        {            routes. Ignoreroute ("{resource}.axd/{*pathinfo}");            Routes. MapRoute (                name: "Default",                URL: "{controller}/{action}/{id}",                defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}            );        

The method is also called in Application_Start.

The key is::: To call the API corresponding to the registered routing method, then call the normal controller's route registration method. Because the author is later added in the project Webapi, so just in the last registered API route, can be inaccessible to. Finally, it is successfully accessed before the normal route is registered!

I don't know if this is a bug in. NET MVC, or that's how it's designed.

Web API cannot access 404

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.