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

WebApi controller added to MVC website Route 404


I'm trying to make a call to a WebApi method from a JavaScript function.

Through Fiddler, I can see that the request being made is:

http://localhost:49601/api/faults?page=1&pageSize=5&filter=&sort=insertedDate+desc

I originally created my website using the MVC template (in Visual Studio 2015). I later added a WebApi controller. I have also added the existing WebApiConfig.cs to the App_Start folder. This remains unchanged:

public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

My new WebApi controller begins as follows:

public class FaultsController : ApiController
{
    private ESBContext _context;
    private IRepository<Fault> FaultRepository;
    private static ILog _logger =
        LogManager.GetLogger(
        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public FaultsController(ESBContext context)
    {
        this.FaultRepository = new EFRepository<Fault>(context);
        _context = context;
        _context.Database.Log = (x => _logger.Debug(x));  //send EF queries via log4net
    }

    public IHttpActionResult GetFaults([FromUri]int page, [FromUri]int pageSize, [FromUri]string filter, [FromUri]string sort)
    {

When the request is made I get a 404 back. Could anyone please tell me where I went wrong?


Solution

  • Found it!

    I needed to add the following to the Application_Start method of Global.asax.cs:

    GlobalConfiguration.Configure(WebApiConfig.Register);