Search code examples
jqueryajaxasp.net-mvc-4asp.net-web-apiasp.net-web-api-routing

How to get Api Controller Uri for getJSON calls?


I'm trying to get the Url of an API Controller for a getJSON call. The repeated answer I've seen pop up on stack does not work:

var elements = [];
$.getJSON("api/MySweetApi/Get", null, function(data) {
    $.each(data, function(index, element) {
        elements.push(element.ReferenceNumber + " - " + element.Description);
    });
});

My ApiController is located in ~/Controllers/api.

Is there a 'best practice' for handling the link out to an MVC api controller? In a perfect world the answer would hook into the routing engine so that if we decide to move our api controllers to ~/api it works without us having to make any changes.

My WebApiConfig is:

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 }
        );
    }
}

Solution

  • This works:

    $.getJSON('@Url.HttpRouteUrl("DefaultApi", new RouteValueDictionary{ {"action","Get"}, {"controller", "MySweetApi"}})', null, function (data) {
        $.each(data, function(index, element) {
            elements.push(element.ReferenceNumber + " - " + element.Description);
        });
    });
    

    However, it seems really verbose and unnecessary.