Correct web-api controller action method definition for jsonp request

五迷三道 提交于 2019-12-13 06:14:03

问题


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 =]


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/17318144/correct-web-api-controller-action-method-definition-for-jsonp-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!