简体   繁体   中英

Call WebAPI GET yielding 404 not found

VS 2017, New, Project, C#, ASP.NET Web app, ASP.NET 4.5.2 Empty Templates.

Unchecked folder and reference for Webforms, MVC and WebAPI. Later added MS WebApi v5.4.2 via Nuget.

Manually added "Controllers" folder.

xController.cs:

namespace v1.MyApiCallTheirApi.api
{
    public class xController : ApiController
    {
        // GET api/<controller>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

index.html:

<body>
    <input type="button" value="Go" onclick="go()"/>
    <script type="text/javascript">
        function go()
        {
            alert("lafdla");
            $.ajax({
                type: "GET",
                url: "/api/x", 
                success: alert("ok")
            });
        }
    </script>
</body>

$.ajax call always returns 404. Already check this , that , and many others. So far my only suspect is it may need a Global.asax for routing config, but I assume after adding API it should auto-add some hidden routing for me.

在此处输入图片说明 在此处输入图片说明

Right now your application doesn't knows how routes are created. MVC cannot know automatically unless you provide the pointers as to where each type of code is located.

Hence two ways out here (using GlobalConfiguration instance):-

a) Convention based, use map route method. No other place requires any further change.

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

b) Use attributes on controller methods to define actual routes. Then add the route attribute on each action method

 config.MapHttpAttributeRoutes();

Over action

[Route('api/myentity/get')
public entity GetEntity() { }

As for adding the package, it only provides you the relevant dlls required for WebAPI, doesn't makes any more changes

You can define the default action of the controller also by the Action attribute [HttpGet("")] .

You need to update your action:

// GET api/<controller>
[HttpGet("")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

As a tip Postman is a nice tool to test your api requests, which is also recommendet by the .NET documentation, see here .

Summarize the WHY and SOLUTION of my problem:

  1. Global.asax
  2. API Routing registration via App_Start
  3. Attribute and Convention routings can't mixed together
  4. Once going Attribute you have to declare attribute for each method.
  5. Although Api controller can be placed anywhere/folder and can be named anything without "Controller" suffix, it must have the "Controller" suffix for class, ie public class v1Controller : ApiController , just public class v1 : ApiController won't work.

Global.asax is optional but it's like _init() of a project, so is a must here because API needs routing. Whether this Api is invoked by in-project or out-of-project, as soon as it's hit the built-in App_Start init everything of the project.

public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }

API routing registration defined in a class typically in App_Start, convention name is WebApiConfig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Either this Attribute Routing
            config.MapHttpAttributeRoutes();

            // Or this conventional Routing, but not together.
            config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

Adding a new package from Nuget won't auto-config/add necessary items to project.

MS WebApi is developed based on MVC routing, it's confused if MVC is needed, here is a good reading . Answer is No, you don't need MVC in order to do WebApi.

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