James D
James D

Reputation: 2291

C# webapi mvc controller added before the /api/{controller}

I've made an API controller and made the suggested changes in other articles. (ref. 404 error after adding Web API to an existing MVC Web Application)

I feel like I'm fairly close to the solution, however my page is still not getting to the correct controller. When I use the F12 tools i can see it's added my MVC controller before my "/api/{controller}". Clearly something is still wrong in my routing but I'm not sure how to fix it?

TimeRegistrations is my MVC controller, api/WorkOrderAPI is the controller I actually need to get to. The route should be /api/WorkOrderAPI. The url is going for this though: Requested URL: /TimeRegistrations/api/WorkOrderAPI

To get the page I want I'm coming from:

localhost:1234/TimeRegistrations/Index

The table needed is loaded onto the page:

localhost:1234/TimeRegistrations/WorkOrderIndex

The table should be requested at

localhost:1234/api/WorkOrderAPI

In my application start I've got:

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

in webApiConfig I've got:

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

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

In routeconfig I've got:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "EmployeeInfo", action = "Index", id = UrlParameter.Optional }
        );
    }

My view code is:

function loadWorkOrders() {
    $.ajax({
        type: "GET",
        url: "api/WorkOrderAPI",
        success: function (data) {
            alert("Success");
            self.WorkOrders(data);
        },
        error: function (err) {
            alert(err.status + " from WorkOrderAPI");
        }
    });

Thanks in advance!

Upvotes: 1

Views: 67

Answers (1)

Shane Ray
Shane Ray

Reputation: 1459

You are using a relative route in your AJAX call. Try this instead

url: "/api/WorkOrderAPI",

Upvotes: 1

Related Questions