0

シンプルな Web API コントローラー アクション メソッドがあります。

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

webapi のデフォルト ルート構成を使用します

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

クロスドメイン呼び出しを行う必要があるため、jsonp 呼び出しを使用します。

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

次の応答が返ってきました (コード 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 はコールバック パラメータを追加します。アクションパラメーターにもマップする必要がありますか? そこは無関係!

任意の助けをいただければ幸いです=]

4

2 に答える 2

2

コントローラー メソッドのパラメーターの名前は、ルート パラメーターと一致する必要があります。メソッドを次のように変更します。

public int GetWeight(int id)
{
    return 5;
}
于 2013-06-26T14:20:46.183 に答える
0

問題はルートにあるようです。変更してみてください:

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

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

GetWeightまたはアクションの名前をIndex

于 2013-06-26T11:03:51.200 に答える