1

次のように、CURL を使用して単純な POST パラメーター (int) を ASP.NET Web API コントローラーの POST メソッドに送信しようとしています。

curl -d "id=1" --ntlm --user <user>:<pass> http://dev.test.local/api/test


これは Curl の POST にデータを添付する正しい方法ですか? URL に問題なく接続できますが、サーバーから次のエラーが返されるため、パラメーター 'id' が渡されないようです。

"The parameters dictionary contains a null entry for parameter 'id' of non-nulla
ble type 'System.Int32' for method 'System.String Post(Int32)' in 'Test.Si
te.Controllers.TestController'. An optional parameter must be a reference type,
a nullable type, or be declared as an optional parameter."


OrderController の POST メソッドは次のとおりです。

    // POST api/test
    public string Post(int id)
    {
        return "Post successful";
    }


どんな助けでも大歓迎です。

4

2 に答える 2

1

問題はintstring、 などの単純なタイプは、以下のように明示的に伝えない限り、メッセージ本文のデータでモデル バインドできないことです。

public string Post([FromBody]int id)
{
    return "Post successful";
}

RouteDataもう 1 つの解決策は、クエリ文字列からこれらのタイプの値を問い合わせることです。

于 2012-08-07T07:18:09.310 に答える
1

個人的には、単純な DTO を使用し、JSON 経由で呼び出します。

ルート:

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}",
            defaults: new {   }
        );

コントローラーと DTO:

[DataContract]
public class valueDto
{
    [DataMember]
    public int id { get; set; }
}

public class TestController : ApiController
{
    // POST api/values
    public string Post(valueDto value)
    {
        return string.Format("Post successful {0}", value.id);
    }
}

curl で呼び出す:

curl -d "{ "id": 1 }" --ntlm --user <user>:<pass> http://dev.test.local/api/test -H "Content-Type:application/json"

しかし

tugberk's answer から少しフォローし、別のanswerhereを参照するだけです。

FromBody 属性を使用する場合は、「Content-Type」も Content-Type: application/x-www-form-urlencoded として送信する必要があります。また、「id=1」を持たない呼び出しを変更し、代わりに「=1」を使用する必要があります。

curl -d "=1" --ntlm --user <user>:<pass> http://dev.test.local/api/test -H "Content-Type:application/x-www-form-urlencoded"
于 2012-08-07T08:12:57.047 に答える