为JSONP请求正确的Web-API控制器的操作方法定义 [英] Correct web-api controller action method definition for jsonp request

查看:191
本文介绍了为JSONP请求正确的Web-API控制器的操作方法定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Web API控制器的操作方法:

I have a simple web api controller action method:

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

我用的WebAPI默认路由配置

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

我需要做跨域调用,这样我使用JSONP电话:

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

我得到如下回应(code 404):

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."

应该是什么适当的措施方法定义映射这个jsnop要求?
正如你看到的JSONP增加了回调参数。是否应该也映射在行动参数?这是irrevelant那里!

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!

任何帮助AP preciated =]

Any help appreciated =]

推荐答案

在你的控制器方法的参数的名称需要匹配的路由参数。你的方法更改为:

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

这篇关于为JSONP请求正确的Web-API控制器的操作方法定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆