I have an MVC application with a few simple pages that will mostly run on Web API calls. For simplicity I want to include them in the same project. I can launch and navigate to my page just fine, but when I try to call my API through Ajax I keep getting a 404 error - it can't 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 in their own folder (called "API") inside my Controllers folder in my project - that's why the namespace contains "API" on this example controller.
When I use F12 on the browser to capture the request getting sent, I can see that my call has the following info:
Request URL: http://localhost:50035/api/User
Request Method: GET
Status Code: 404 / Not Found
Now my understanding is that this should find the API with the name UserController and find the function with the [HttpGet] tag with no arguments, then return the string array ("value1", "value2"). Instead it doesn't find anything.
As a final note, here is my routing config (and yes, it is being initialized on Global.asax):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
UPDATE:
Based on the feedback I've received so far, I moved my Global.asax configuration around. 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 doesn't return a success message. It just hangs. I do not get the "Success!" alert.