Search code examples
c#asp.net-web-apiasp.net-web-api-routing

All my routes are failing in my Web Api app


I've created a simple Web Api app that was working earlier this evening. However after installing Ninject and having some trouble with reinstalling references (accidentally removed some when uninstalling Ninject with Nuget).

I figure it could possibly be due to my Startup.cs file:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);

        app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }

    private StandardKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }
}

Here is one of my controllers:

[RoutePrefix("api/Books")]

public class BooksController : ApiController { private IBookService _bookService;

private BooksController(IBookService bookService)
{
    _bookService = bookService;
}

[Route("GetAllBooks")]
public IEnumerable<Book> GetAllBooks()
{
    return _bookService.GetAllBooks();
}

[Route("GetBook")]
public IHttpActionResult GetBook(string isbn)
{
    var book = _bookService.GetBook(isbn);

    if (book == null)
        return NotFound();

    return Ok(book);
}

However every call I make to any of these routes returns 404, e.g.:

http://localhost/api/Books/GetAllBooks

As you can see, I'm using Ninject with Owin so I'm not sure if this is contributing to the problem.

Anyone seen this before or have any ideas?


Solution

  • I see that you're using attribute routing. In order for it to work, you need to call config.MapHttpAttributeRoutes();:

    HttpConfiguration config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();