0

I'm trying create a simple API and call it from my html. I made something similar earlier today but I can't get this one to work. It just returns a 404 error.

script from HTML

 <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
                    var uri = 'api/books';
                    $(document).ready(function () {
                        $.getJSON(uri)
                            .done(function (data) {
                                $.each(data, function (key, item) {
                                    $('<li>', { text: formatItem(item) }).appendTo($('#books'));
                                });
                            });
                    });

api controller

using WebApplication1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace WebApplication1.Controllers
{

    public class BookController : ApiController
    {

        [HttpGet]
        [Route("api/books")]
        public IHttpActionResult ShowAllProducts()
        {
            var db = new DbSearchQuery();
            return Ok(db.LoadBooks());
        }

    }
}

EDIT:

WebApiConfig.cs

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
4
  • Seems that your route looks like host/api/api/Book. Try to remove your first slug api in annotation for action method. Well, you can check your requests in browser dev tools so. Commented Apr 10, 2016 at 20:36
  • You are sure your LoadBooks return correct json? According to the jquery documentation: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently Commented Apr 10, 2016 at 20:43
  • I am fairly certain, because I created another proof of concept Solution in which I pulled this from the same data base were the Query was the exact same. I just added the same api controller and jquery to another solution where this api will be used. Commented Apr 10, 2016 at 20:49
  • @suavocado Check URL of your GET request. Commented Apr 10, 2016 at 20:59

3 Answers 3

1

Try using relative to rootpaths. You missing a backslash in your uri. Change uri as following :

var uri = '/api/books';

and make sure you have config.MapHttpAttributeRoutes(); in your WebApiConfig.Register() method.

EDIT 1

You can view the details of network errors ( like 404 ) in console section of your browser's developer tools. Just hit F12 in your browser to activate developer tools window and take a look at console tab. You'll probably see that your ajax call targeting a different location than www.yoursite.com/api/books

Sign up to request clarification or add additional context in comments.

1 Comment

@suavocado make sure your application is running ( check that url in browser ) and can you verify that you are making the ajax request within the same url ( just to rule out the cors problems )
1

Start by changing your controller code:

using WebApplication1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    [RoutePrefix("api/books")]
    public class BookController : ApiController
    {

        [HttpGet]
        [Route("")]
        public IHttpActionResult ShowAllProducts()
        {
            var db = new DbSearchQuery();
            return Ok(db.LoadBooks());
        }

    }

}

Then double check that your Ajax call is made to the correct address: http://yourhost/api/books looking at your browser console.

[Edit after comments]

Please check if your project contains a startup class. If you are using Owin then you have to create a Startup.cs file for bootstrapping your application. A basic example can be found below:

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;

[assembly: OwinStartup(typeof(WebApplication1.Startup))]

namespace WebApplication1
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);

            app.UseWebApi(config);
        }
   }
}

More about how to start Owin based web application here What is the new Startup.cs file for in Visual Studio 2013 projects?

7 Comments

Ajax call is going to the correct http://..../api/books and has been, but still getting the the 404
Can you add your Startup.cs and WebApiConfig.cs code?
Just added it, let me know if you need anything else.
Please post also your Startup.cs file, with the current code I have no other suggestions for you.
Edited the answer after your last comments
|
0

added Global.aspx

namespace WebApplication1
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.