mbudnik
mbudnik

Reputation: 2107

Correct web-api controller action method definition for jsonp request

I have a simple web api controller action method:

public class WeightController : ApiController
{
    [HttpGet]
    [AcceptVerbs("GET")]
    public int GetWeight(int weightId)
    {
        return 5;
    }
}

I use default route config for webapi

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

I need to do cross domain call so I use jsonp call:

$.ajax({
        url: 'api/Weight/1',
        type: 'GET',
        dataType: 'jsonp',
        crossDomain: true,
        success: function(data) {
            alert('success:' + data);
        },
        error: function(jqXHR,status,error) {
            alert('error');
        }
    });

I'm getting the following response (code 404):

"No HTTP resource was found that matches the request URI
'http://localhost:31836/api/Weight/1?callback=jQuery18204532131106388192_1372242854823&_=1372242854950'.",
"MessageDetail":"No action was found on the controller 'Weight' that matches the request."

What should be the proper action method definition to map this jsnop request? As you see jsonp adds the callback parameter. Should it be also mapped in action parameters? It is irrevelant there!

Any help appreciated =]

Upvotes: 0

Views: 3096

Answers (2)

Jon Susiak
Jon Susiak

Reputation: 4978

The name of the parameter in your controller method needs to match the route parameter. Change your method to:

public int GetWeight(int id)
{
    return 5;
}

Upvotes: 2

YD1m
YD1m

Reputation: 5895

Seems like problem is in route. Try modify:

config.Routes.MapHttpRoute(
            name: "DefaultApi",

            routeTemplate: "api/{controller}/{id}",
            defaults: new { 
                  id = RouteParameter.Optional,
                  action = "GetWeight"
             }
        );

or rename GetWeight action to Index

Upvotes: 0

Related Questions