I have an MVC application with a few simple pages that will basically run when the Web API is called. For simplicity, I want to include them in the same project. I can start and go to my page just fine, but when I try to call my API through Ajax, I get a 404 error all the time - it cannot find the API function.
Here is my javascript file:
$(document).ready(function () { //set the login button to call our test API function document.getElementById("login_submit").addEventListener("click", GetUser); }); function GetUser() { var response = $.ajax({ url: '/api/User', method: 'GET', contentType: 'application/json; charset=utf-8', success: function (data) { alert("Success!"); }, error: function (request, status, error) { alert(error); } }); }
And here is my controller:
namespace MyProject.Controllers.API { public class UserController : ApiController { // GET api/<controller> [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/<controller>/5 [HttpGet] public string Get(int id) { return "value"; } } }
The API controllers are located in their own folder (called the "API") inside my Controllers folder in my project - why the namespace contains an "API" on this sample controller.
When I use F12 in the browser to capture the request being sent, I see that my call has the following information:
Request URL: http://localhost:50035/api/User Request Method: GET Status Code: 404 / Not Found
Now I understand that this should find an API called UserController and find a function with the [HttpGet] tag without arguments, and then return an array of strings ("value1", "value2"). Instead, he finds nothing.
As a final note, here is my routing configuration (and yes, it initializes to Global.asax):
public static class WebApiConfig { public static void Register(HttpConfiguration config) {
UPDATE:
Based on the feedback I have received so far, I have moved my Global.asax configuration. It now looks like this:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
Now, when I call my API function, I get ... Pending. It does not return a success message. He is just hanging. I do not get "Success!". a warning.