0

WebAPI テクノロジを使用しているあるサーバーから別のサーバーにリクエストを投稿しようとしています。これは、呼び出しを受け取る私のメソッドです

[HttpGet]
    [HttpPost]
    public HttpResponseMessage MyMethod([FromBody] string token, [FromBody] string email, [FromBody] string password)
    {

        string a = "hello world!";
        return new HttpResponseMessage() { Content = new StringContent(a) };
    }

私はそれに投稿するこのコードを使用しています:

using (var c = new WebClient())
        {
            //string obj = ":" + JsonConvert.SerializeObject(new { token= "token", email="email", password="password" });
            NameValueCollection myNameValueCollection = new NameValueCollection();

            // Add necessary parameter/value pairs to the name/value container.
            myNameValueCollection.Add("token", "token");
            myNameValueCollection.Add("email", "email");

            myNameValueCollection.Add("password", "password");

            byte[] responseArray = c.UploadValues("MyServer/MyMethod", "POST", myNameValueCollection);


            return Encoding.ASCII.GetString(responseArray);
        }

私はいくつかの代替案を試しました。

私が上に書いたものは、内部サーバーエラーを引き起こし、MyMethod 内の私のブレークポイントはヒットしないため、問題は私のメソッドのコードにはありません。

nameValueCollection にパラメーターを追加する 3 行をコメントすると、404 が返されます。

MyMethod の署名からパラメーターを削除すると、機能します。

この情報を、API をホストするサーバーに投稿したいと考えています。

私が間違っていることを知っていますか?

4

1 に答える 1

1

いつものように、ビューモデルを書くことから始めます:

public class MyViewModel 
{
    public string Token { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

コントローラーアクションがパラメーターとして受け取ること:

[HttpPost]
public HttpResponseMessage MyMethod(MyViewModel model)
{

    string a = "hello world!";
    return new HttpResponseMessage() { Content = new StringContent(a) };
}

[HttpGet]属性を削除したことに注意してください。動詞を選ばなければなりません。ところで、標準の ASP.NET Web API ルーティング規則に従う場合、アクションの名前は、それにアクセスするために使用されている HTTP 動詞に対応している必要があります。これは標準の RESTful 規則です。

今、あなたはそれを打つことができます:

using (var c = new WebClient())
{
    var myNameValueCollection = new NameValueCollection();

        // Add necessary parameter/value pairs to the name/value container.
    myNameValueCollection.Add("token", "token");
    myNameValueCollection.Add("email", "email");
    myNameValueCollection.Add("password", "password");

    byte[] responseArray = c.UploadValues("MyServer/MyMethod", "POST", myNameValueCollection);

    return Encoding.ASCII.GetString(responseArray);
}
于 2013-09-29T18:53:59.947 に答える